Merge branch 'omaha_16.1.1' into field_16.1.1

Change-Id: I9da773e70da7bb8d62253093f20aebd8aea328f6

Former-commit-id: 0c909272ebdaf4ce94195b54a021a38c1e174ff3
This commit is contained in:
Ana Rivera 2015-07-20 15:56:51 +00:00
commit 9a33597d6e
102 changed files with 1572 additions and 1278 deletions

View file

@ -53,4 +53,4 @@ export SITE_IDENTIFIER=${AW_SITE_IDENTIFIER}
# set Fax environment variables pointing to ldad@ls1
export LDAD_EXTERNAL_HOME=/ldad
export LDAD_EXTERNAL_PUBLIC=/data/ldad/public
export AWIPS2_TEMP=/awips2/tmp

View file

@ -148,4 +148,14 @@ if [ $DEBUG_FLAG == "on" ]; then
echo "To Debug ... Connect to Port: ${EDEX_DEBUG_PORT}."
fi
#create tmp dir
mkdir -p ${AWIPS2_TEMP}
RC=$?
if [ ${RC} -ne 0 ]; then
echo "ERROR: Failed to create temp directory ${AWIPS2_TEMP}."
echo "Unable To Continue ... Terminating."
exit 1
fi
java -Xmx32m -XX:MaxPermSize=12m -XX:ReservedCodeCacheSize=4m -jar ${YAJSW_HOME}/wrapper.jar -c ${EDEX_HOME}/conf/${CONF_FILE} ${WRAPPER_ARGS}

View file

@ -185,7 +185,7 @@
<property name="initialListeners">
<list>
<!-- This causes database tables to be initialized when a db plugin is registered -->
<bean class="com.raytheon.uf.edex.database.schema.SchemaManager" factory-method="getInstance"/>
<bean class="com.raytheon.uf.edex.database.plugin.SchemaManager" factory-method="getInstance"/>
</list>
</property>
<property name="initialProperties">

View file

@ -91,7 +91,7 @@ wrapper.java.additional.4=-Dorg.apache.camel.jmx.disabled=true
wrapper.java.additional.5=-Duser.timezone=GMT
# Set default tmp to awips controlled directory for security
wrapper.java.additional.6=-Djava.io.tmpdir=/awips2/tmp
wrapper.java.additional.6=-Djava.io.tmpdir=${AWIPS2_TEMP}
# garbage collection settings
wrapper.java.additional.gc.1=-XX:+UseConcMarkSweepGC

View file

@ -117,12 +117,12 @@ public class AlertViewLocalizationPrefStore implements AlertViewPrefStore,
@Override
public void addListener(AlertViewPrefListener listener) {
listeners.remove(listener);
listeners.add(listener);
}
@Override
public void removeListener(AlertViewPrefListener listener) {
listeners.add(listener);
listeners.remove(listener);
}
@Override

View file

@ -1,6 +1,6 @@
<popUpPreferences>
<filter>error</filter>
<duration>3000</duration>
<duration>5000</duration>
<width>500</width>
<height>50</height>
<corner>LOWER_RIGHT</corner>

View file

@ -80,7 +80,7 @@ public class PopUpPreferences {
public PopUpPreferences() {
/* Everything needs reasonable defaults to keep PreferenceFile happy. */
filter = Priority.ERROR.name().toLowerCase();
duration = 3000;
duration = 5000;
corner = PopUpCorner.LOWER_RIGHT;
width = 500;
height = 50;

View file

@ -21,10 +21,13 @@ package com.raytheon.uf.viz.alertview.ui.popup;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
@ -109,6 +112,21 @@ public class AlertPopup implements AlertDestination,
*/
private class PopupAlertTask implements Runnable {
private static final int UNBLOCK = 0;
private static final int BLOCK = 1;
/**
* Counter for generating unique keys for {@link UnblockPopupTask}s.
*/
private int nextDelayUnblockKey = 2;
/**
* The popup becomes blocked and will not close or update if the
* {@link MouseTracker} detects that the mouse is over the popup.
*/
private AtomicInteger blockingState = new AtomicInteger(UNBLOCK);
private final Timer timer = new Timer("Remove Alert Popup");
private Shell shell;
@ -159,12 +177,37 @@ public class AlertPopup implements AlertDestination,
public void openInAlertView() {
if (displayedAlert != null) {
OpenAlertViewHandler.openInAlertView(displayedAlert);
blockingState.set(UNBLOCK);
clear(displayedAlert);
}
}
public void blockChanges() {
this.blockingState.set(BLOCK);
}
public void unblockChanges() {
if (blockingState.compareAndSet(BLOCK, nextDelayUnblockKey)) {
timer.schedule(new UnblockPopupTask(nextDelayUnblockKey), 500);
nextDelayUnblockKey += 1;
}
}
public void unblockChanges(int key) {
if (blockingState.compareAndSet(key, UNBLOCK)) {
Display.getDefault().asyncExec(PopupAlertTask.this);
}
}
@Override
public void run() {
if (blockingState.get() != UNBLOCK) {
return;
} else {
/* Reset count to prevent wrap-around.*/
nextDelayUnblockKey = 2;
}
this.displayedAlert = this.alert;
if (displayedAlert != null && (shell == null || shell.isDisposed())) {
shell = new Shell(Display.getDefault(), SWT.NO_FOCUS
@ -233,6 +276,7 @@ public class AlertPopup implements AlertDestination,
}
shell.setLocation(startX, startY);
new MouseTracker(label);
shell.setVisible(true);
}
if (displayedAlert == null) {
@ -273,4 +317,108 @@ public class AlertPopup implements AlertDestination,
task.clear(alert);
}
}
/**
* This task is scheduled from the UI thread when the {@link MouseTracker}
* detects that the mouse is no longer over the popup. It will cause the
* {@link PopupAlertTask} to refresh. If the user moves the mouse over the
* popup before this task is executed then the {@link PopupAlertTask} will
* invalidate the key and ignore the request to unblock when this task runs.
*/
private class UnblockPopupTask extends TimerTask {
private final int key;
public UnblockPopupTask(int key) {
this.key = key;
}
@Override
public void run() {
task.unblockChanges(key);
}
}
/**
* Change the cursor and color when the mouse is over the popup. Also
* prevents the popup from changing when the mouse is over it.
*/
private class MouseTracker implements
MouseTrackListener {
private final Label label;
private final Shell shell;
/** True when mouse is in the popup. */
private boolean active = false;
private Color inactiveColor;
private Color activeColor;
public MouseTracker(Label label) {
this.label = label;
this.shell = label.getShell();
label.addMouseTrackListener(this);
}
private void activate() {
if (!active) {
shell.setCursor(shell.getDisplay().getSystemCursor(
SWT.CURSOR_HAND));
if (activeColor == null
|| !inactiveColor.equals(label.getBackground())) {
inactiveColor = label.getBackground();
int r = inactiveColor.getRed();
int g = inactiveColor.getGreen();
int b = inactiveColor.getBlue();
if (r + b + g < 32) {
/* If its a really dark color, make it brighter */
r = Math.min(255, r + 32);
g = Math.min(255, g + 32);
b = Math.min(255, b + 32);
} else {
/* If its a bright color make it darker */
r = Math.max(0, r - 32);
g = Math.max(0, g - 32);
b = Math.max(0, b - 32);
}
if (activeColor != null) {
activeColor.dispose();
}
activeColor = new Color(shell.getDisplay(), r, g, b);
}
label.setBackground(activeColor);
active = true;
task.blockChanges();
}
}
private void deactivate() {
if (active) {
shell.setCursor(shell.getDisplay().getSystemCursor(
SWT.CURSOR_ARROW));
label.setBackground(inactiveColor);
active = false;
task.unblockChanges();
}
}
@Override
public void mouseEnter(MouseEvent e) {
activate();
}
@Override
public void mouseExit(MouseEvent e) {
deactivate();
}
@Override
public void mouseHover(MouseEvent e) {
activate();
}
}
}

View file

@ -236,8 +236,11 @@ public class StylePreferencePage extends PreferencePage implements
}
protected void deleteStyle() {
table.getSelection()[0].dispose();
styleSelected();
TableItem[] selection = table.getSelection();
if (selection != null && selection.length > 0) {
selection[0].dispose();
styleSelected();
}
}
protected void styleSelected() {

View file

@ -297,8 +297,10 @@ public class AlertTable extends Composite implements StyleListener {
public void select(Alert alert) {
if (alertsToAdd.contains(alert)) {
TableItem item = addAlertInternal(alert);
alertTable.setSelection(alertTable.indexOf(item));
alertSelected();
if (item != null) {
alertTable.setSelection(alertTable.indexOf(item));
alertSelected();
}
return;
}
for (TableItem item : alertTable.getItems()) {
@ -433,11 +435,10 @@ public class AlertTable extends Composite implements StyleListener {
@Override
public void updateStyle() {
Display display = getDisplay();
if (display.isDisposed()) {
if (this.isDisposed()){
return;
}
display.asyncExec(new Runnable() {
getDisplay().asyncExec(new Runnable() {
@Override
public void run() {

View file

@ -79,7 +79,7 @@ import com.raytheon.uf.viz.alertviz.config.AlertMetadata;
*
*/
public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
MouseListener {
MouseListener, DisposeListener {
private static final int MAX_INITIAL_LINES = 5;
private static final int WIDTH_IN_CHARS = 135;
@ -266,9 +266,9 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
private Label fillerLbl;
/**
* Listens for "Hide Dialog" event, implemented by AlertVisualization class
* Listens for Hide and Dispose events
*/
private final Listener hideListener;
private final Listener eventListener;
/**
* Initialized flag indicating if the control have been initialized.
@ -289,14 +289,14 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
* @param expanded
* Expanded flag.
* @param listener
* Hide listener.
* Event listener.
* @param startUpRGB
* Color to be displayed at startup.
*/
public AlertPopupMessageDlg(Shell parent, StatusMessage statMsg,
boolean expanded, Listener listener, RGB startUpRGB) {
super(parent, 0);
hideListener = listener;
eventListener = listener;
statMsgArray.add(statMsg);
this.expanded = expanded;
this.first = true;
@ -314,6 +314,8 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
shell = new Shell(parent, SWT.ON_TOP | SWT.RESIZE);
shell.setText("Alert Visualization Popup Message Dialog");
shell.addDisposeListener(this);
// Create the main layout for the shell.
GridLayout mainLayout = new GridLayout(1, false);
mainLayout.marginWidth = 0;
@ -330,28 +332,28 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
setBackgroundColors(startUp);
// listener event triggers when shell set to not be visible
shell.addListener(SWT.Hide, hideListener);
shell.addListener(SWT.Hide, eventListener);
shell.addListener(SWT.Dispose, eventListener);
}
shell.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
while (statMsgArray.size() != 0) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
bgColor.dispose();
@Override
public void widgetDisposed(DisposeEvent e) {
while (statMsgArray.size() != 0) {
if (!display.readAndDispatch()) {
display.sleep();
}
});
}
bgColor.dispose();
initialized = false;
labelFont.dispose();
}
/**
* Open method used to display the dialog.
*
* @return True/False/null.
*/
public Object open() {
private void open() {
setInitialDialogLocation();
@ -366,12 +368,6 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
display.sleep();
}
}
initialized = false;
labelFont.dispose();
return null;
}
/**
@ -553,7 +549,7 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
ackAllBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
acknowledgeAllMessages(true);
acknowledgeAllMessages();
}
});
@ -782,9 +778,6 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
}
msgLogList.select(currentIndex);
if (initialized == true) {
showDialog(true);
}
}
/**
@ -900,7 +893,7 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
/**
* Acknowledge all of the messages.
*/
public void acknowledgeAllMessages(boolean confirmPrompt) {
public void acknowledgeAllMessages() {
int index = msgLogList.getSelectionIndex();
int result = SWT.CANCEL;
@ -914,28 +907,26 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
showHideLog();
}
if (confirmPrompt) {
ConfirmationDlg cd = new ConfirmationDlg(shell,
"Are you sure you want to acknowledge all popup messages?",
SWT.ICON_QUESTION);
ConfirmationDlg cd = new ConfirmationDlg(shell,
"Are you sure you want to acknowledge all popup messages?",
SWT.ICON_QUESTION);
if ((msgLogList != null) && !msgLogList.isDisposed()) {
Rectangle logBounds = msgLogList.getBounds();
Point logDisplayOrigin = msgLogList.toDisplay(0, 0);
logBounds.x = logDisplayOrigin.x;
logBounds.y = logDisplayOrigin.y;
cd.setAvoidedArea(logBounds);
}
result = cd.open();
if (result != SWT.YES) {
if ((result == SWT.CANCEL) && expandedForPrompt) {
expanded = false;
showHideLog();
}
return;
if ((msgLogList != null) && !msgLogList.isDisposed()) {
Rectangle logBounds = msgLogList.getBounds();
Point logDisplayOrigin = msgLogList.toDisplay(0, 0);
logBounds.x = logDisplayOrigin.x;
logBounds.y = logDisplayOrigin.y;
cd.setAvoidedArea(logBounds);
}
result = cd.open();
if (result != SWT.YES) {
if ((result == SWT.CANCEL) && expandedForPrompt) {
expanded = false;
showHideLog();
}
return;
}
String userName = System.getProperty("user.name");
@ -987,17 +978,21 @@ public class AlertPopupMessageDlg extends Dialog implements MouseMoveListener,
}
/**
* Shows or hides the dialog.
* Shows the dialog.
*
* @param show
* True to show dialog, false to hide.
*/
public void showDialog(boolean show) {
shell.setLocation(dialogXY);
shell.setVisible(show);
public void showDialog() {
if (initialized) {
shell.setLocation(dialogXY);
shell.setVisible(true);
showSelectedListData();
msgLogList.showSelection();
showSelectedListData();
msgLogList.showSelection();
} else {
open();
}
}
/**

View file

@ -1,4 +1,5 @@
/**
* 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
@ -21,7 +22,6 @@ package com.raytheon.uf.viz.alertviz.ui.dialogs;
import java.io.File;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
@ -359,7 +359,7 @@ public class AlertVisualization implements ITimerAction, IAudioAction,
*/
private void createTray() {
trayItem = new TrayItem(tray, SWT.NONE);
addToolTip();
updateToolTip();
trayItemMenu = new Menu(shell, SWT.POP_UP);
@ -378,9 +378,7 @@ public class AlertVisualization implements ITimerAction, IAudioAction,
@Override
public void widgetSelected(SelectionEvent e) {
if ((alertPopupDlg != null)
&& (alertPopupDlg.getNumberOfMessages() > 0)) {
cancelTimer();
if (alertPopupDlg != null) {
openAlertPopupDialog();
}
}
@ -459,9 +457,7 @@ public class AlertVisualization implements ITimerAction, IAudioAction,
showPopup.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (alertPopupDlg != null) {
openAlertPopupDialog();
}
openAlertPopupDialog();
}
});
@ -471,19 +467,13 @@ public class AlertVisualization implements ITimerAction, IAudioAction,
ackAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
// Verify user meant to acknowledge all messages
boolean rval = MessageDialog.openConfirm(shell, "Confirm",
"Acknowledge all messages?");
if (rval == true) {
if (alertPopupDlg != null) {
alertPopupDlg.acknowledgeAllMessages(false);
alertPopupDlg = null;
addToolTip();
ackAll.setEnabled(false);
showPopup.setEnabled(false);
}
cancelTimer();
if (alertPopupDlg != null) {
alertPopupDlg.showDialog();
alertPopupDlg.acknowledgeAllMessages();
} else {
// should never happen
Container.logInternal(Priority.ERROR,
"alertPopupDlg unexpectedly null");
}
}
});
@ -699,16 +689,17 @@ public class AlertVisualization implements ITimerAction, IAudioAction,
// Pop-up message
if (amd.isPopup() == true) {
if ((alertPopupDlg == null) || (alertPopupDlg.isDisposed() == true)) {
if (alertPopupDlg == null) {
alertPopupDlg = new AlertPopupMessageDlg(shell, statMsg,
gConfig.isExpandedPopup(), this, amd.getBackground());
showPopup.setEnabled(true);
ackAll.setEnabled(true);
startBlinkTrayTimer();
} else {
alertPopupDlg.addNewMessage(statMsg, amd);
}
startBlinkTrayTimer();
addToolTip();
showPopup.setEnabled(true);
ackAll.setEnabled(true);
updateToolTip();
if (doNotDisturb == false) {
openAlertPopupDialog();
}
@ -747,15 +738,12 @@ public class AlertVisualization implements ITimerAction, IAudioAction,
* Opens the alert pop-up dialog
*/
public void openAlertPopupDialog() {
if ((alertPopupDlg != null) && (alertPopupDlg.dialogIsOpen() == true)) {
alertPopupDlg.showDialog(true);
if (alertPopupDlg != null) {
alertPopupDlg.showDialog();
} else {
alertPopupDlg.open();
alertPopupDlg = null;
cancelTimer();
addToolTip();
ackAll.setEnabled(false);
showPopup.setEnabled(showAlertDlg);
// should never happen
Container.logInternal(Priority.ERROR,
"alertPopupDlg unexpectedly null");
}
}
@ -785,7 +773,7 @@ public class AlertVisualization implements ITimerAction, IAudioAction,
* Adds a tool tip to the tray icon, if messages need to be acknowledged,
* shows the number, otherwise displays general text.
*/
private void addToolTip() {
private void updateToolTip() {
if (alertPopupDlg == null) {
this.trayItem.setToolTipText("AlertViz Menu");
} else {
@ -819,10 +807,26 @@ public class AlertVisualization implements ITimerAction, IAudioAction,
*/
@Override
public void handleEvent(Event event) {
ackAll.setEnabled(true);
showPopup.setEnabled(true);
startBlinkTrayTimer();
addToolTip();
switch (event.type) {
case SWT.Hide:
ackAll.setEnabled(true);
showPopup.setEnabled(true);
startBlinkTrayTimer();
updateToolTip();
break;
case SWT.Dispose:
alertPopupDlg = null;
cancelTimer();
updateToolTip();
ackAll.setEnabled(false);
showPopup.setEnabled(false);
break;
default:
Container.logInternal(Priority.WARN, "Unexpected event type: "
+ event.type);
break;
}
}
@Override

View file

@ -49,7 +49,6 @@ import com.raytheon.uf.viz.core.VizConstants;
import com.raytheon.uf.viz.core.comm.PerspectiveSpecificLoadProperties;
import com.raytheon.uf.viz.core.drawables.AbstractDescriptor;
import com.raytheon.uf.viz.core.drawables.AbstractRenderableDisplay;
import com.raytheon.uf.viz.core.drawables.FrameCoordinator;
import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.IDescriptor.FramesInfo;
import com.raytheon.uf.viz.core.drawables.IRenderableDisplay;
@ -82,7 +81,8 @@ import com.raytheon.uf.viz.d2d.core.D2DLoadProperties;
* like A1.
* May 5, 2014 3265 bsteffen Better handling of resources returning
* null dataTimes.
*
* May 13, 2015 4461 bsteffen Move the logic to change frames into the
* FrameCoordinator.
*
* </pre>
*
@ -254,8 +254,6 @@ public class D2DTimeMatcher extends AbstractTimeMatcher {
}
}
}
FramesInfo currInfo = descriptor.getFramesInfo();
// Find the times for the time match basis.
DataTime[] timeSteps = findBasisTimes(descriptor.getResourceList(),
descriptor.getNumberOfFrames());
@ -278,9 +276,21 @@ public class D2DTimeMatcher extends AbstractTimeMatcher {
}
// Update the descriptor to the new times.
int dateIndex = determineNewIndex(descriptor, currInfo, timeSteps);
descriptor.setFramesInfo(new FramesInfo(timeSteps, dateIndex,
resourceTimeMap));
if ((timeMatchBasis.getDescriptor() != null)
&& (timeMatchBasis.getDescriptor() != descriptor)) {
int idx = timeMatchBasis.getDescriptor().getFramesInfo()
.getFrameIndex();
if ((idx >= 0) && (idx < timeSteps.length)) {
descriptor.setFramesInfo(new FramesInfo(timeSteps, idx,
resourceTimeMap));
} else {
descriptor.setFramesInfo(new FramesInfo(timeSteps,
resourceTimeMap));
}
} else {
descriptor.setFramesInfo(new FramesInfo(timeSteps,
resourceTimeMap));
}
// Add Remove data for all the resources.
for (Entry<AbstractVizResource<?, ?>, DataTime[]> entry : resourceTimeMap
@ -292,95 +302,6 @@ public class D2DTimeMatcher extends AbstractTimeMatcher {
}
}
private int indexToUpdateTo(IDescriptor descriptor, DataTime[] oldTimes,
int oldIndex, DataTime[] frames, int startFrame) {
int frameToUse = startFrame;
IRenderableDisplay display = descriptor.getRenderableDisplay();
if ((display != null) && (display.getContainer() != null)) {
IDisplayPaneContainer container = display.getContainer();
if (container.getLoopProperties().isLooping()) {
return frameToUse;
}
}
switch (descriptor.getFrameCoordinator().getAnimationMode()) {
case Latest: {
if (oldIndex == (oldTimes.length - 1)) {
frameToUse = frames.length - 1;
}
break;
}
case Temporal: {
// was our old time the last frame for that time?
boolean wasLastForTime = (oldIndex == FrameCoordinator
.getLastTimeIndex(oldTimes, oldIndex));
if (wasLastForTime) {
// check if a new time came in for our frame
int latestForTime = FrameCoordinator.getLastTimeIndex(frames,
startFrame);
if (latestForTime > startFrame) {
frameToUse = latestForTime;
}
}
break;
}
case Vertical: {
boolean wasLastForTime = (oldIndex == FrameCoordinator
.getLastVerticalIndex(oldTimes, oldIndex));
if (wasLastForTime) {
frameToUse = FrameCoordinator.getLastVerticalIndex(frames,
startFrame);
}
}
}
return frameToUse;
}
/**
* Determines the new time index for a descriptor
*
* @param descriptor
* the descriptor
* @param timeSteps
* the list of times for the time match basis.
* @return
*/
private int determineNewIndex(IDescriptor descriptor, FramesInfo currInfo,
DataTime[] timeSteps) {
if ((timeSteps == null) || (timeSteps.length == 0)) {
return -1;
}
// If possible just copy from the time match basis
if ((timeMatchBasis.getDescriptor() != null)
&& (timeMatchBasis.getDescriptor() != descriptor)) {
int idx = timeMatchBasis.getDescriptor().getFramesInfo()
.getFrameIndex();
if ((idx >= 0) && (idx < timeSteps.length)) {
return idx;
}
}
// Next try to get the closest time to
DataTime[] origSteps = currInfo.getFrameTimes();
int curIndex = currInfo.getFrameIndex();
if ((origSteps != null) && (curIndex >= 0)
&& (curIndex < origSteps.length)) {
DataTime startTime = origSteps[curIndex];
int dateIndex = Arrays.binarySearch(timeSteps, startTime);
if (dateIndex < 0) {
if (timeSteps[0].getMatchValid() > startTime.getMatchValid()) {
return 0;
}
} else {
dateIndex = indexToUpdateTo(descriptor, origSteps, curIndex,
timeSteps, dateIndex);
if ((dateIndex >= 0) && (dateIndex < (timeSteps.length - 1))) {
return dateIndex;
}
}
}
// if that didn't work just return the last frame
return timeSteps.length - 1;
}
/**
* Recursively determine times for all resource, or if it is an
* IResourceGroup then for all resources in it.

View file

@ -36,6 +36,7 @@ import org.geotools.data.DataUtilities;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
@ -84,6 +85,8 @@ import com.vividsolutions.jts.geom.Polygon;
* Jun 18, 2015 4354 dgilling Allow each polygon to have their own
* properties.
* Jul 01, 2015 4375 dgilling Fix setDefaultPolygon.
* Jul 07, 2015 4375 dgilling Better error message for loadJob, make it
* INFO level, fix geotools CRS warning.
*
* </pre>
*
@ -135,7 +138,7 @@ public class DamagePathLayer<T extends DamagePathResourceData> extends
// reset the polygon if the localization file is invalid.
if (polygons.isEmpty()) {
statusHandler
.error("The damage path file was invalid. The polygon has been reset.");
.info("The previously saved damage path file didn't contain any polygons. Resetting to default polygon.");
setDefaultPolygon();
}
} else {
@ -306,6 +309,7 @@ public class DamagePathLayer<T extends DamagePathResourceData> extends
SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
typeBuilder.setName("feature");
typeBuilder.setCRS(DefaultGeographicCRS.WGS84);
Geometry polygon = damagePath.getPolygon();
typeBuilder.setDefaultGeometry("the_geom");
typeBuilder.add("the_geom", polygon.getClass());

View file

@ -504,14 +504,14 @@ class SmartScript(BaseTool.BaseTool):
else:
result = result[0];
slice = result.getGridSlice()
result = slice.getNDArray()
if type(result) is ndarray and result.dtype == numpy.int8:
retVal = slice.getNDArray()
if type(retVal) is ndarray and retVal.dtype == numpy.int8:
# discrete or weather
keys = JUtil.javaObjToPyVal(slice.getKeyList())
retVal = (result, keys)
elif type(result) is not numpy.ndarray and len(result) == 2:
retVal = (retVal, keys)
elif type(retVal) is not numpy.ndarray and len(retVal) == 2:
# vector
retVal = tuple(result)
retVal = tuple(retVal)
if retVal is None or retVal == []:
if noDataError == 1:
@ -1702,12 +1702,8 @@ class SmartScript(BaseTool.BaseTool):
def getLatLonGrids(self):
gridLoc = self.getGridLoc()
latLonGrid = gridLoc.getLatLonGrid().getNDArray();
# FIXME We reverse the x and y dimensions because that's what AWIPS 1
# did and that makes the pre-existing python code compatible. Java
# ordering is x,y while python is ordering is y,x. So our latlonGrid
# here has ordering y, x but gridLoc is a Java object so we have to
# get the values from it in reverse.
latLonGrid = gridLoc.getLatLonGrid()
latLonGrid = numpy.reshape(latLonGrid, (2,gridLoc.getNy().intValue(),gridLoc.getNx().intValue()), order='F')
return latLonGrid[1], latLonGrid[0]

View file

@ -24,6 +24,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@ -50,6 +51,7 @@ import com.raytheon.uf.common.dataquery.db.QueryResult;
import com.raytheon.uf.common.geospatial.MapUtil;
import com.raytheon.uf.common.geospatial.util.WorldWrapCorrector;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.util.Pair;
import com.raytheon.uf.viz.core.DrawableString;
import com.raytheon.uf.viz.core.IExtent;
import com.raytheon.uf.viz.core.IGraphicsTarget;
@ -109,7 +111,7 @@ import com.vividsolutions.jts.io.WKBReader;
* Aug 21, 2014 #3459 randerso Restructured Map resource class hierarchy
* Sep 04, 2014 #3365 ccody Changes for removing Data_Delivery dependencies
* Apr 06, 2015 #17340 randerso Eliminated clipping to GFE domain, code cleanup
*
* Jul 13, 2015 4500 rjpeter Fix SQL Injection concerns.
* </pre>
*
* @author randerso
@ -117,6 +119,7 @@ import com.vividsolutions.jts.io.WKBReader;
*/
public class ZoneSelectorResource extends DbMapResource {
private static final String EDIT_AREA = "editarea";
private static final RGB NO_ZONE_COLOR;
static {
@ -147,12 +150,15 @@ public class ZoneSelectorResource extends DbMapResource {
String query;
List<String> columns;
Request(IGraphicsTarget target, IMapDescriptor descriptor,
ZoneSelectorResource rsc, String query) {
ZoneSelectorResource rsc, String query, List<String> columns) {
this.target = target;
this.descriptor = descriptor;
this.rsc = rsc;
this.query = query;
this.columns = columns;
}
}
@ -177,10 +183,10 @@ public class ZoneSelectorResource extends DbMapResource {
}
}
private ArrayBlockingQueue<Request> requestQueue = new ArrayBlockingQueue<Request>(
private final ArrayBlockingQueue<Request> requestQueue = new ArrayBlockingQueue<Request>(
QUEUE_LIMIT);
private ArrayBlockingQueue<Result> resultQueue = new ArrayBlockingQueue<Result>(
private final ArrayBlockingQueue<Result> resultQueue = new ArrayBlockingQueue<Result>(
QUEUE_LIMIT);
private boolean canceled;
@ -190,11 +196,12 @@ public class ZoneSelectorResource extends DbMapResource {
}
public void request(IGraphicsTarget target, IMapDescriptor descriptor,
ZoneSelectorResource rsc, String query) {
ZoneSelectorResource rsc, String query, List<String> columns) {
if (requestQueue.size() == QUEUE_LIMIT) {
requestQueue.poll();
}
requestQueue.add(new Request(target, descriptor, rsc, query));
requestQueue.add(new Request(target, descriptor, rsc, query,
columns));
this.cancel();
this.schedule();
@ -222,6 +229,10 @@ public class ZoneSelectorResource extends DbMapResource {
QueryResult mappedResult = DirectDbQuery
.executeMappedQuery(req.query, "maps",
QueryLanguage.SQL);
int index = 0;
for (String column : req.columns) {
mappedResult.addColumnName(column, index++);
}
// long t1 = System.currentTimeMillis();
// System.out.println("Maps DB query took: " + (t1 - t0)
@ -540,9 +551,9 @@ public class ZoneSelectorResource extends DbMapResource {
}
}
private MapQueryJob queryJob;
private final MapQueryJob queryJob;
private Map<String, ZoneInfo> zoneData;
private final Map<String, ZoneInfo> zoneData;
private List<String> limitZones;
@ -556,7 +567,7 @@ public class ZoneSelectorResource extends DbMapResource {
private IShadedShape shapeList[];
private GeometryFactory geomFactory;
private final GeometryFactory geomFactory;
private IGraphicsTarget target;
@ -566,9 +577,9 @@ public class ZoneSelectorResource extends DbMapResource {
private Envelope boundingEnvelope;
private GridLocation gloc;
private final GridLocation gloc;
private WorldWrapCorrector worldWrapCorrector;
private final WorldWrapCorrector worldWrapCorrector;
/**
* @param data
@ -716,8 +727,10 @@ public class ZoneSelectorResource extends DbMapResource {
clipToProjExtent(screenExtent).getEnvelope())) {
if (!paintProps.isZooming()) {
PixelExtent clippedExtent = clipToProjExtent(screenExtent);
String query = buildQuery(clippedExtent, simpLev);
queryJob.request(aTarget, descriptor, this, query);
Pair<String, List<String>> queryPair = buildQuery(
clippedExtent, simpLev);
queryJob.request(aTarget, descriptor, this,
queryPair.getFirst(), queryPair.getSecond());
lastExtent = clippedExtent;
lastSimpLev = simpLev;
}
@ -828,7 +841,8 @@ public class ZoneSelectorResource extends DbMapResource {
}
}
protected String buildQuery(PixelExtent extent, double simpLev) {
protected Pair<String, List<String>> buildQuery(PixelExtent extent,
double simpLev) {
DecimalFormat df = new DecimalFormat("0.######");
String suffix = "_"
@ -837,16 +851,19 @@ public class ZoneSelectorResource extends DbMapResource {
String geometryField = resourceData.getGeomField() + suffix;
// get the geometry field
List<String> columns = new LinkedList<>();
StringBuilder query = new StringBuilder("SELECT AsBinary(");
query.append(geometryField);
query.append(") as ");
query.append(geometryField);
columns.add(geometryField);
// add any additional columns
if (resourceData.getColumns() != null) {
for (ColumnDefinition column : resourceData.getColumns()) {
query.append(", ");
query.append(column);
columns.add(column.toString());
}
}
@ -863,7 +880,7 @@ public class ZoneSelectorResource extends DbMapResource {
query.append(';');
return query.toString();
return new Pair<>(query.toString(), columns);
}
/**
@ -890,7 +907,7 @@ public class ZoneSelectorResource extends DbMapResource {
IShadedShape newShadedShape = target.createShadedShape(false,
new GeneralGridGeometry(descriptor.getGridGeometry()), true);
// new GeneralGridGeometry(descriptor.getGridGeometry()));
// new GeneralGridGeometry(descriptor.getGridGeometry()));
JTSCompiler shapeCompiler = new JTSCompiler(newShadedShape, null,
descriptor);
JTSGeometryData geomData = shapeCompiler.createGeometryData();
@ -947,39 +964,41 @@ public class ZoneSelectorResource extends DbMapResource {
public List<String> getZoneNames() {
if (zoneData.isEmpty()) {
try {
StringBuilder query = new StringBuilder("SELECT ");
// add any additional columns
int count = 0;
boolean hasEditArea = false;
if (resourceData.getColumns() != null) {
for (ColumnDefinition column : resourceData.getColumns()) {
if (count > 0) {
query.append(", ");
if (EDIT_AREA.equals(column.toString())) {
hasEditArea = true;
break;
}
query.append(column);
count++;
}
}
// add the geometry table
query.append(" FROM ");
query.append(resourceData.getTable());
// add any constraints
String[] constraints = resourceData.getConstraints();
if ((constraints != null) && (constraints.length > 0)) {
query.append(" WHERE ").append(
StringUtils.join(constraints, " AND "));
}
if (hasEditArea) {
StringBuilder query = new StringBuilder("SELECT ");
query.append(EDIT_AREA);
query.append(" FROM ");
// add the geometry table
query.append(resourceData.getTable());
query.append(';');
// add any constraints
String[] constraints = resourceData.getConstraints();
if ((constraints != null) && (constraints.length > 0)) {
query.append(" WHERE ").append(
StringUtils.join(constraints, " AND "));
}
QueryResult mappedResult = DirectDbQuery.executeMappedQuery(
query.toString(), "maps", QueryLanguage.SQL);
query.append(';');
QueryResult mappedResult = DirectDbQuery
.executeMappedQuery(query.toString(), "maps",
QueryLanguage.SQL);
if (mappedResult.getColumnNames().containsKey("editarea")) {
for (int i = 0; i < mappedResult.getResultCount(); i++) {
String zoneName = (String) mappedResult
.getRowColumnValue(i, "editarea");
.getRowColumnValue(i, 0);
getZoneInfo(zoneName);
}
}
@ -1056,15 +1075,14 @@ public class ZoneSelectorResource extends DbMapResource {
WKBReader wkbReader = new WKBReader();
for (int i = 0; i < mappedResult.getResultCount(); i++) {
String zoneName = (String) mappedResult.getRowColumnValue(
i, "editarea");
i, 1);
if ((this.limitZones != null)
&& !this.limitZones.contains(zoneName)) {
continue;
}
byte[] b = (byte[]) mappedResult.getRowColumnValue(i,
"extent");
byte[] b = (byte[]) mappedResult.getRowColumnValue(i, 0);
if (b != null) {
Geometry geom = wkbReader.read(b);

View file

@ -62,8 +62,6 @@ import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.grid.rsc.AbstractGridResource;
import com.raytheon.uf.viz.core.grid.rsc.data.GeneralGridData;
import com.raytheon.uf.viz.core.rsc.LoadProperties;
import com.raytheon.viz.grid.rsc.general.AbstractGridResource;
import com.raytheon.viz.grid.rsc.general.GeneralGridData;
import com.raytheon.viz.lightning.LightningResourceData.DisplayType;
import com.raytheon.viz.lightning.cache.LightningFrame;
import com.raytheon.viz.lightning.cache.LightningFrameMetadata;

View file

@ -39,7 +39,7 @@
<vmArgsWin>-Dfile.encoding=UTF-8 -Xmx2560M</vmArgsWin>
</launcherArgs>
<windowImages/>
<windowImages i16="/com.raytheon.viz.ui.personalities.awips/cave_16x16.png" i32="/com.raytheon.viz.ui.personalities.awips/cave_32x32.png" i48="/com.raytheon.viz.ui.personalities.awips/cave_48x48.png" i64="/com.raytheon.viz.ui.personalities.awips/cave_64x64.png" i128="/com.raytheon.viz.ui.personalities.awips/cave_128x128.png"/>
<splash
location="com.raytheon.viz.ui.personalities.awips"
@ -50,18 +50,19 @@
<solaris/>
<win useIco="false">
<bmp
winSmallHigh="/com.raytheon.viz.ui.personalities.awips/alertViz_icon16x16_32bit.bmp"
winSmallLow="/com.raytheon.viz.ui.personalities.awips/alertViz_icon16x16_8bit.bmp"
winMediumHigh="/com.raytheon.viz.ui.personalities.awips/alertViz_icon32x32_32bit.bmp"
winMediumLow="/com.raytheon.viz.ui.personalities.awips/alertViz_icon32x32_8bit.bmp"
winLargeHigh="/com.raytheon.viz.ui.personalities.awips/alertViz_icon48x48_32bit.bmp"
winLargeLow="/com.raytheon.viz.ui.personalities.awips/alertViz_icon48x48_8bit.bmp"/>
winSmallHigh="/com.raytheon.viz.ui.personalities.awips/cave_16x16_32bit.bmp"
winSmallLow="/com.raytheon.viz.ui.personalities.awips/cave_16x16_8bit.bmp"
winMediumHigh="/com.raytheon.viz.ui.personalities.awips/cave_32x32_32bit.bmp"
winMediumLow="/com.raytheon.viz.ui.personalities.awips/cave_32x32_8bit.bmp"
winLargeHigh="/com.raytheon.viz.ui.personalities.awips/cave_48x48_32bit.bmp"
winLargeLow="/com.raytheon.viz.ui.personalities.awips/cave_48x48_8bit.bmp"
winExtraLargeHigh="/com.raytheon.viz.ui.personalities.awips/cave_256x256_32bit.bmp"/>
</win>
</launcher>
<vm>
<linux include="true">jdk1.6.0</linux>
<windows include="true">jdk1.6.0</windows>
<linux include="true">jdk1.7.0</linux>
<windows include="true">jdk1.7.0</windows>
</vm>
<plugins>

View file

@ -38,7 +38,7 @@
<vmArgsWin>-Dfile.encoding=UTF-8</vmArgsWin>
</launcherArgs>
<windowImages/>
<windowImages i16="/com.raytheon.viz.ui.personalities.awips/cave_16x16.png" i32="/com.raytheon.viz.ui.personalities.awips/cave_32x32.png" i48="/com.raytheon.viz.ui.personalities.awips/cave_48x48.png" i64="/com.raytheon.viz.ui.personalities.awips/cave_64x64.png" i128="/com.raytheon.viz.ui.personalities.awips/cave_128x128.png"/>
<splash
location="com.raytheon.viz.ui.personalities.awips"
@ -53,7 +53,7 @@
</launcher>
<vm>
<windows include="true">jdk1.6.0</windows>
<windows include="true">jdk1.7.0</windows>
</vm>
<plugins>

Binary file not shown.

After

Width:  |  Height:  |  Size: 622 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View file

@ -57,6 +57,10 @@
name="startupForegroundColor"
value="000000">
</property>
<property
name="windowImages"
value="icons/cave_16x16.gif,icons/cave_32x32.gif">
</property>
</product>
</extension>
</plugin>

View file

@ -37,7 +37,7 @@
<vmArgsWin>-Dfile.encoding=UTF-8 -Xmx2560M</vmArgsWin>
</launcherArgs>
<windowImages/>
<windowImages i16="/com.raytheon.viz.ui.personalities.awips/cave_16x16.png" i32="/com.raytheon.viz.ui.personalities.awips/cave_32x32.png" i48="/com.raytheon.viz.ui.personalities.awips/cave_48x48.png" i64="/com.raytheon.viz.ui.personalities.awips/cave_64x64.png" i128="/com.raytheon.viz.ui.personalities.awips/cave_128x128.png"/>
<splash
location="com.raytheon.viz.ui.personalities.awips"
@ -48,18 +48,19 @@
<solaris/>
<win useIco="false">
<bmp
winSmallHigh="/com.raytheon.viz.ui.personalities.awips/alertViz_icon16x16_32bit.bmp"
winSmallLow="/com.raytheon.viz.ui.personalities.awips/alertViz_icon16x16_8bit.bmp"
winMediumHigh="/com.raytheon.viz.ui.personalities.awips/alertViz_icon32x32_32bit.bmp"
winMediumLow="/com.raytheon.viz.ui.personalities.awips/alertViz_icon32x32_8bit.bmp"
winLargeHigh="/com.raytheon.viz.ui.personalities.awips/alertViz_icon48x48_32bit.bmp"
winLargeLow="/com.raytheon.viz.ui.personalities.awips/alertViz_icon48x48_8bit.bmp"/>
winSmallHigh="/com.raytheon.viz.ui.personalities.awips/cave_16x16_32bit.bmp"
winSmallLow="/com.raytheon.viz.ui.personalities.awips/cave_16x16_8bit.bmp"
winMediumHigh="/com.raytheon.viz.ui.personalities.awips/cave_32x32_32bit.bmp"
winMediumLow="/com.raytheon.viz.ui.personalities.awips/cave_32x32_8bit.bmp"
winLargeHigh="/com.raytheon.viz.ui.personalities.awips/cave_48x48_32bit.bmp"
winLargeLow="/com.raytheon.viz.ui.personalities.awips/cave_48x48_8bit.bmp"
winExtraLargeHigh="/com.raytheon.viz.ui.personalities.awips/cave_256x256_32bit.bmp"/>
</win>
</launcher>
<vm>
<linux include="true">jdk1.6.0</linux>
<windows include="true">jdk1.6.0</windows>
<linux include="true">jdk1.7.0</linux>
<windows include="true">jdk1.7.0</windows>
</vm>
<plugins>

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.viz.radar.frame;
import com.raytheon.uf.common.time.DataTime;
/**
*
* A {@link DataTime} that also contains information about the volume scan time
* and the elevation number for the time it represents. This is used by the
* {@link SailsFrameCoordinator}
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------- -------- ----------- --------------------------
* May 13, 2015 4461 bsteffen Initial creation
*
* </pre>
*
* @author bsteffen
* @version 1.0
*/
public class RadarDataTime extends DataTime {
private static final long serialVersionUID = 1L;
private Integer elevationNumber;
private int volumeScanNumber;
public RadarDataTime(DataTime time) {
super(time.getRefTime());
}
public Integer getElevationNumber() {
return elevationNumber;
}
public void setElevationNumber(Integer elevationNumber) {
this.elevationNumber = elevationNumber;
}
public int getVolumeScanNumber() {
return volumeScanNumber;
}
public void setVolumeScanNumber(int volumeScanNumber) {
this.volumeScanNumber = volumeScanNumber;
}
}

View file

@ -0,0 +1,113 @@
/**
* 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.viz.radar.frame;
import java.util.HashMap;
import java.util.Map;
import com.raytheon.uf.common.time.DataTime;
/**
*
* A cache of the most recently viewed frame time. The cache is keyed off the
* volume scan number and the primary elevation angle and will return the most
* recently viewed frame time for the key.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------- -------- ----------- --------------------------
* May 13, 2015 4461 bsteffen Initial creation
*
* </pre>
*
* @author bsteffen
* @version 1.0
*/
public class RadarFrameCache {
private Map<Key, RadarDataTime> cache = new HashMap<>();
/**
* This should be called whenever a frame is displayed to update the cache
*/
public void setLastFrameTime(DataTime time) {
if (time instanceof RadarDataTime) {
RadarDataTime rtime = (RadarDataTime) time;
cache.put(new Key(rtime), rtime);
}
}
/**
* Get the most recent displayed frame that matches the volume scan and
* elevation angle of the provided time. If no time is in the cache then the
* time is returned.
*/
public RadarDataTime getLastFrameTime(RadarDataTime otherTime) {
RadarDataTime result = cache.get(new Key(otherTime));
if(result == null){
result = otherTime;
}
return result;
}
private static class Key {
private final int volumeScanNumber;
private final double primaryElevationAngle;
private final int hashCode;
public Key(RadarDataTime time) {
this.volumeScanNumber = time.getVolumeScanNumber();
this.primaryElevationAngle = time.getLevelValue();
long temp = Double.doubleToLongBits(primaryElevationAngle);
int hashCode = 31 + (int) (temp ^ (temp >>> 32));
hashCode = 31 * hashCode + volumeScanNumber;
this.hashCode = hashCode;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Key other = (Key) obj;
if (Double.doubleToLongBits(primaryElevationAngle) != Double
.doubleToLongBits(other.primaryElevationAngle))
return false;
if (volumeScanNumber != other.volumeScanNumber)
return false;
return true;
}
}
}

View file

@ -0,0 +1,286 @@
/**
* 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.viz.radar.frame;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.viz.core.drawables.AbstractDescriptor;
import com.raytheon.uf.viz.core.drawables.FrameCoordinator;
import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.IDescriptor.IFrameChangedListener;
import com.raytheon.uf.viz.core.drawables.IFrameCoordinator;
import com.raytheon.viz.radar.ui.RadarDisplayManager;
/**
*
* A specialized frame coordinator which introduces specialized behavior when
* the time match basis is a radar resource and that radar is in
* SAILS(Supplemental Adaptive Intra-Volume Low-Level Scan) mode. Many of the
* operations are the same as a normal {@link FrameCoordinator} except the
* following:
*
* <ul>
* <li>When the last frame is displayed it will go to the frame with the highest
* elevation number that is part of the last volume scan. The opposite is true
* when going to the first frame.
*
* <li>When traversing the vertical dimension all frames in the same volume scan
* will be considered even if the reftimes are different. When choosing between
* multiple frames with the same volume scan and elevation angle the frame that
* was most recently viewed will be used.
*
* </ul>
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------- -------- ----------- --------------------------
* May 13, 2015 4461 bsteffen Initial creation
*
* </pre>
*
* @author bsteffen
* @version 1.0
*/
public class SailsFrameCoordinator extends FrameCoordinator implements
IFrameChangedListener {
private final RadarFrameCache cache;
private final RadarDisplayManager displayManager;
public SailsFrameCoordinator(IDescriptor descriptor) {
super(descriptor);
cache = new RadarFrameCache();
descriptor.addFrameChangedListener(this);
this.displayManager = RadarDisplayManager.getInstance();
IFrameCoordinator existing = descriptor.getFrameCoordinator();
currentAnimationMode = existing.getAnimationMode();
}
protected boolean isEnabled() {
return displayManager.getCurrentSettings().isSailsFrameCoordinator();
}
@Override
protected int getLastVerticalIndex(DataTime[] frames, int dataIndex,
IFrameValidator validator) {
if (isEnabled()) {
List<RadarDataTime> volumeScan = getVolumeScan(frames, dataIndex);
Collections.sort(volumeScan, new ElevationAngleComparator<>());
Collections.reverse(volumeScan);
for (RadarDataTime time : volumeScan) {
if (validator.isValid(time)) {
return getBestFrameIndex(frames, time, validator);
}
}
}
return super.getLastVerticalIndex(frames, dataIndex, validator);
}
@Override
protected int getFirstVerticalIndex(DataTime[] frames, int dataIndex,
IFrameValidator validator) {
if (isEnabled()) {
List<RadarDataTime> volumeScan = getVolumeScan(frames, dataIndex);
Collections.sort(volumeScan, new ElevationAngleComparator<>());
for (RadarDataTime time : volumeScan) {
if (validator.isValid(time)) {
return getBestFrameIndex(frames, time, validator);
}
}
}
return super.getLastVerticalIndex(frames, dataIndex, validator);
}
@Override
protected int getNextVerticalIndex(DataTime[] frames, int dataIndex,
FrameChangeOperation op, IFrameValidator validator) {
if (isEnabled()) {
if (op == FrameChangeOperation.NEXT) {
List<RadarDataTime> volumeScan = getVolumeScan(frames,
dataIndex);
Collections.sort(volumeScan, new ElevationAngleComparator<>());
int startIdx = volumeScan.indexOf(frames[dataIndex]);
double currentLevel = volumeScan.get(startIdx).getLevelValue();
int idx = (startIdx + 1) % volumeScan.size();
while (idx != startIdx) {
RadarDataTime time = volumeScan.get(idx);
if (validator.isValid(time)
&& time.getLevelValue() != currentLevel) {
return getBestFrameIndex(frames, time, validator);
}
idx = (idx + 1) % volumeScan.size();
}
} else if (op == FrameChangeOperation.PREVIOUS) {
List<RadarDataTime> volumeScan = getVolumeScan(frames,
dataIndex);
Collections.sort(volumeScan, new ElevationAngleComparator<>());
int startIdx = volumeScan.indexOf(frames[dataIndex]);
double currentLevel = volumeScan.get(startIdx).getLevelValue();
int idx = (startIdx + volumeScan.size() - 1)
% volumeScan.size();
while (idx != startIdx) {
RadarDataTime time = volumeScan.get(idx);
if (validator.isValid(time)
&& time.getLevelValue() != currentLevel) {
return getBestFrameIndex(frames, time, validator);
}
idx = (idx + volumeScan.size() - 1) % volumeScan.size();
}
}
}
return super.getNextVerticalIndex(frames, dataIndex, op, validator);
}
@Override
protected int getLastDataTimeIndex(DataTime[] frames, int dataIndex,
IFrameValidator validator) {
int idx = super.getLastDataTimeIndex(frames, dataIndex, validator);
if (isEnabled()) {
List<RadarDataTime> volumeScan = getVolumeScan(frames, idx);
Collections.sort(volumeScan, new ElevationNumberComparator());
Collections.reverse(volumeScan);
for (RadarDataTime time : volumeScan) {
if (validator.isValid(time)) {
return Arrays.asList(frames).indexOf(time);
}
}
}
return idx;
}
@Override
protected int getFirstDataTimeIndex(DataTime[] frames, int dataIndex,
IFrameValidator validator) {
int idx = super.getFirstDataTimeIndex(frames, dataIndex, validator);
if (isEnabled()) {
List<RadarDataTime> volumeScan = getVolumeScan(frames, idx);
Collections.sort(volumeScan, new ElevationNumberComparator());
for (RadarDataTime time : volumeScan) {
if (validator.isValid(time)) {
return Arrays.asList(frames).indexOf(time);
}
}
}
return idx;
}
/**
* Given an example time, find the best time in the frames that has the same
* volume scan number and primary elevation angle. This is done by
* consulting the cache to see if there is a previously viewed frame that
* can be used.
*/
private int getBestFrameIndex(DataTime[] frames, RadarDataTime example,
IFrameValidator validator) {
List<DataTime> framesList = Arrays.asList(frames);
DataTime cached = cache.getLastFrameTime(example);
int index = framesList.indexOf(cached);
if (index >= 0 && validator.isValid(frames[index])) {
return index;
} else {
return framesList.indexOf(example);
}
}
/**
* Get a list of all the {@link DataTime} in frames that are an instance of
* {@link RadarDataTime} and have the same volume scan number as the
* DataTime at the provided index.
*/
private static List<RadarDataTime> getVolumeScan(DataTime[] frames,
int dataIndex) {
DataTime example = frames[dataIndex];
if (example instanceof RadarDataTime) {
int volumeScanNumber = ((RadarDataTime) example)
.getVolumeScanNumber();
long exampleRef = example.getRefTime().getTime();
List<RadarDataTime> result = new ArrayList<>();
for (DataTime frame : frames) {
if (frame instanceof RadarDataTime) {
RadarDataTime radarTime = (RadarDataTime) frame;
if (radarTime.getVolumeScanNumber() == volumeScanNumber) {
long timeRef = radarTime.getRefTime().getTime();
long diff = Math.abs(exampleRef - timeRef);
if (diff < TimeUtil.MILLIS_PER_HOUR) {
result.add(radarTime);
}
}
}
}
return result;
}
return Collections.emptyList();
}
public static void addToDescriptor(IDescriptor descriptor) {
IFrameCoordinator current = descriptor.getFrameCoordinator();
if (current instanceof SailsFrameCoordinator) {
return;
}
if (descriptor instanceof AbstractDescriptor) {
current = new SailsFrameCoordinator(descriptor);
((AbstractDescriptor) descriptor).setFrameCoordinator(current);
}
}
/**
* Used for sorting times based off elevation angle.
*/
private static class ElevationAngleComparator<T extends DataTime>
implements Comparator<T> {
@Override
public int compare(T time1, T time2) {
return Double.compare(time1.getLevelValue(), time2.getLevelValue());
}
}
/**
* Used for sorting times based off elevation number.
*/
private static class ElevationNumberComparator implements
Comparator<RadarDataTime> {
@Override
public int compare(RadarDataTime time1, RadarDataTime time2) {
return Integer.compare(time1.getElevationNumber(),
time2.getElevationNumber());
}
}
@Override
public void frameChanged(IDescriptor descriptor, DataTime oldTime,
DataTime newTime) {
cache.setLastFrameTime(newTime);
}
}

View file

@ -62,6 +62,7 @@ import com.raytheon.uf.viz.d2d.core.time.ID2DTimeMatchingExtension;
import com.raytheon.uf.viz.d2d.core.time.TimeMatcher;
import com.raytheon.viz.radar.DefaultVizRadarRecord;
import com.raytheon.viz.radar.VizRadarRecord;
import com.raytheon.viz.radar.frame.SailsFrameCoordinator;
import com.raytheon.viz.radar.interrogators.IRadarInterrogator;
import com.raytheon.viz.radar.rsc.RadarTextResource.IRadarTextGeneratingResource;
import com.raytheon.viz.radar.textcontributors.IRadarTextContributor;
@ -82,6 +83,7 @@ import com.vividsolutions.jts.geom.Coordinate;
* Apr 11, 2013 16030 D. Friedman Fix NPE.
* May 5, 2014 17201 D. Friedman Enable same-radar time matching.
* Jun 11, 2014 2061 bsteffen Move rangeable methods to radial resource
* May 13, 2015 4461 bsteffen Add sails frame coordinator.
*
* </pre>
*
@ -179,6 +181,7 @@ public class AbstractRadarResource<D extends IDescriptor> extends
*/
@Override
protected void initInternal(IGraphicsTarget target) throws VizException {
SailsFrameCoordinator.addToDescriptor(descriptor);
RadarTextResourceData.addRadarTextResource(descriptor);
}

View file

@ -52,6 +52,8 @@ import com.raytheon.viz.radar.interrogators.IRadarInterrogator;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Feb 23, 2009 chammack Initial creation
* May 13, 2015 4461 bsteffen Invalidate time cache on all updates
* for SAILS.
*
* </pre>
*
@ -229,6 +231,16 @@ public class RadarResourceData extends AbstractRequestableResourceData {
return all;
}
@Override
public void update(Object updateData) {
super.update(updateData);
/*
* The available time cache will contain DataTime objects when it needs
* to contain RadarDataTime objects so it must be invalidated.
*/
invalidateAvailableTimesCache();
}
@Override
public void update(AlertMessage... messages) {
for (AlertMessage message : messages) {
@ -242,6 +254,7 @@ public class RadarResourceData extends AbstractRequestableResourceData {
}
}
super.update(messages);
invalidateAvailableTimesCache();
}
}

View file

@ -20,11 +20,10 @@
package com.raytheon.viz.radar.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
@ -54,6 +53,7 @@ import com.raytheon.viz.ui.dialogs.CaveSWTDialog;
* ------------ ---------- ----------- --------------------------
* 04 DEC 2007 373 lvenable Initial creation
* 06 Nov 2014 DCS 16776 zwang Add control for MBA
* May 13, 2015 4461 bsteffen Add option for sails.
*
* </pre>
*
@ -132,7 +132,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
* Show MBA Wind Shear check box.
*/
private Button showMbaWindShear;
/**
* Overlap Mesos check box.
*/
@ -193,6 +193,11 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
*/
private Spinner speedSpnr;
/**
* enable sails frame coordinator check box.
*/
private Button enableSails;
/**
* Constructor.
*
@ -234,6 +239,8 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
addSeparator();
createSrmControls();
createCustomStormMotionGroup();
addSeparator();
createSailsControls();
createCloseButton();
updateDialogFromValues();
@ -294,6 +301,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
speedSpnr.setSelection(values.getSrmSpeed());
enableCustomStormControls(values.getSrmSource().equals(
RadarSRMResource.SRMSource.CUSTOM));
enableSails.setSelection(values.isSailsFrameCoordinator());
}
/**
@ -323,18 +331,14 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
showStormScale.setPageIncrement(1);
showStormScale.setLayoutData(gd);
showStormScale.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
showStormLbl.setText(String.valueOf(showStormScale
.getSelection()));
}
});
showStormScale.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
showStormScale.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
@ -372,6 +376,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
}
stiTrackToShowCbo.setLayoutData(gd);
stiTrackToShowCbo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setStiTrackType(RadarDisplayManager.TrackTypes
.fromString(stiTrackToShowCbo.getText()));
@ -429,6 +434,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
lowPohCbo.setLayoutData(gd);
lowPohCbo.setLayoutData(gd);
lowPohCbo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (lowPohCbo.getSelectionIndex() > highPohCbo
.getSelectionIndex()) {
@ -459,6 +465,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
lowPoshCbo.setLayoutData(gd);
lowPoshCbo.setLayoutData(gd);
lowPoshCbo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (lowPoshCbo.getSelectionIndex() > highPoshCbo
.getSelectionIndex()) {
@ -490,6 +497,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
highPohCbo.setLayoutData(gd);
highPohCbo.setLayoutData(gd);
highPohCbo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (lowPohCbo.getSelectionIndex() > highPohCbo
.getSelectionIndex()) {
@ -519,6 +527,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
highPoshCbo.setLayoutData(gd);
highPoshCbo.setLayoutData(gd);
highPoshCbo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (lowPoshCbo.getSelectionIndex() > highPoshCbo
.getSelectionIndex()) {
@ -555,6 +564,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
showElevatedTvsChk = new Button(tvsComp, SWT.CHECK);
showElevatedTvsChk.setText("Show elevated TVS");
showElevatedTvsChk.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setTvsShowElevated(showElevatedTvsChk.getSelection());
}
@ -586,6 +596,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
showExtrapolatedChk = new Button(dmdMdTvsComp, SWT.CHECK);
showExtrapolatedChk.setText("Show extrapolated features");
showExtrapolatedChk.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setDmdMdTvsShowExtrapolated(showExtrapolatedChk
.getSelection());
@ -617,6 +628,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
minFeatureScale.setMaximum(15);
minFeatureScale.setLayoutData(gd);
minFeatureScale.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
minFeatureScaleLbl.setText(String.valueOf(minFeatureScale
.getSelection()));
@ -642,6 +654,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
overlapMesosChk.setText("Show overlapping Mesos");
overlapMesosChk.setLayoutData(gd);
overlapMesosChk.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setDmdShowOverlapping(overlapMesosChk.getSelection());
}
@ -662,6 +675,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
}
dmdTrackToShowCbo.setLayoutData(gd);
dmdTrackToShowCbo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setDmdTrackType(RadarDisplayManager.TrackTypes
.fromString(dmdTrackToShowCbo.getText()));
@ -687,6 +701,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
showMbaWindShear = new Button(mbaComp, SWT.CHECK);
showMbaWindShear.setText("Show Wind Shear");
showMbaWindShear.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setMbaShowWindShear(showMbaWindShear.getSelection());
}
@ -708,6 +723,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
stormMotionRdo = new Button(srmComp, SWT.RADIO);
stormMotionRdo.setText("Storm Motion from WarnGen Track");
stormMotionRdo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setSrmSource(RadarSRMResource.SRMSource.WARNGEN);
enableCustomStormControls(false);
@ -724,6 +740,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
averageStormRdo = new Button(srmComp, SWT.RADIO);
averageStormRdo.setText("Average Storm Motion from STI");
averageStormRdo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setSrmSource(RadarSRMResource.SRMSource.STI);
enableCustomStormControls(false);
@ -736,6 +753,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
customStormRdo = new Button(srmComp, SWT.RADIO);
customStormRdo.setText("Custom Storm Motion");
customStormRdo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setSrmSource(RadarSRMResource.SRMSource.CUSTOM);
enableCustomStormControls(true);
@ -768,9 +786,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
dirScale.setMaximum(359);
dirScale.setIncrement(5);
dirScale.setLayoutData(gd);
dirScale.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
}
dirScale.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
@ -778,9 +794,6 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
dirSpnr.setSelection(dirScale.getSelection());
}
@Override
public void mouseDown(MouseEvent e) {
}
});
gd = new GridData(30, SWT.DEFAULT);
@ -788,9 +801,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
dirSpnr.setLayoutData(gd);
dirSpnr.setMinimum(dirScale.getMinimum());
dirSpnr.setMaximum(dirScale.getMaximum());
dirSpnr.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
}
dirSpnr.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
@ -798,9 +809,6 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
dirScale.setSelection(dirSpnr.getSelection());
}
@Override
public void mouseDown(MouseEvent e) {
}
});
// Filler label
@ -837,9 +845,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
speedScale.setMaximum(99);
speedScale.setIncrement(5);
speedScale.setLayoutData(gd);
speedScale.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
}
speedScale.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
@ -847,9 +853,6 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
speedSpnr.setSelection(speedScale.getSelection());
}
@Override
public void mouseDown(MouseEvent e) {
}
});
gd = new GridData(30, SWT.DEFAULT);
@ -857,9 +860,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
speedSpnr.setLayoutData(gd);
speedSpnr.setMinimum(speedScale.getMinimum());
speedSpnr.setMaximum(speedScale.getMaximum());
speedSpnr.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
}
speedSpnr.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
@ -867,9 +868,6 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
speedScale.setSelection(speedSpnr.getSelection());
}
@Override
public void mouseDown(MouseEvent e) {
}
});
// Filler label
@ -892,6 +890,31 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
spdMaxLbl.setLayoutData(gd);
}
private void createSailsControls() {
Composite sailsComp = new Composite(shell, SWT.NONE);
GridLayout gl = new GridLayout(2, false);
sailsComp.setLayout(gl);
GridData gd = new GridData(60, SWT.DEFAULT);
Label mbaLbl = new Label(sailsComp, SWT.NONE);
mbaLbl.setFont(labelFont);
mbaLbl.setForeground(getDisplay().getSystemColor(SWT.COLOR_BLUE));
mbaLbl.setText("SAILS");
mbaLbl.setLayoutData(gd);
enableSails = new Button(sailsComp, SWT.CHECK);
enableSails.setText("Enable SAILS Frame Coordinator");
enableSails
.setToolTipText("The SAILS frame coordinator enables custom actions for the up/down arrows and the last frame button that");
enableSails.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
values.setSailsFrameCoordinator(enableSails.getSelection());
}
});
}
/**
* Create the close button.
*/
@ -908,6 +931,7 @@ public class RadarDisplayControlDlg extends CaveSWTDialog {
closeBtn.setText("Close");
closeBtn.setLayoutData(gd);
closeBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
shell.dispose();
}

View file

@ -30,6 +30,7 @@ import com.raytheon.viz.radar.ui.RadarDisplayManager.TrackTypes;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 11/06/2014 DCS 16776 zwang Add control for MBA
* May 13, 2015 4461 bsteffen Add option for sails.
*
* </pre>
*
@ -74,6 +75,8 @@ public class RadarDisplayControls {
private boolean showAll;
private boolean sailsFrameCoordinator;
public RadarDisplayControls() {
}
@ -383,4 +386,16 @@ public class RadarDisplayControls {
RadarDisplayManager.getInstance().displayConfigUpdated();
}
}
public boolean isSailsFrameCoordinator() {
return sailsFrameCoordinator;
}
public void setSailsFrameCoordinator(boolean sailsFrameCoordinator) {
if (sailsFrameCoordinator != this.sailsFrameCoordinator) {
this.sailsFrameCoordinator = sailsFrameCoordinator;
RadarDisplayManager.getInstance().displayConfigUpdated();
}
}
}

View file

@ -46,7 +46,7 @@ import com.raytheon.viz.radar.rsc.image.RadarSRMResource.SRMSource;
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
*
* May 13, 2015 4461 bsteffen Add option for sails.
*
* </pre>
*
@ -222,6 +222,8 @@ public class RadarDisplayManager {
prefs.setValue("SRM_Source", currentValues.getSrmSource().name());
prefs.setValue("SRM_Direction", currentValues.getSrmDir());
prefs.setValue("SRM_Speed", currentValues.getSrmSpeed());
prefs.setValue("SAILS_FrameCoordinator",
currentValues.isSailsFrameCoordinator());
// Put the IO on a different thread to avoid hanging.
saveJob.schedule();
}
@ -234,6 +236,7 @@ public class RadarDisplayManager {
IPersistentPreferenceStore prefs = Activator.getDefault()
.getPreferenceStore();
prefs.setDefault("SAILS_FrameCoordinator", true);
RadarDisplayControls currentVals = currentValues;
if (currentVals == null) {
@ -262,6 +265,8 @@ public class RadarDisplayManager {
.getString("SRM_Source")));
currentVals.setSrmDir(prefs.getInt("SRM_Direction"));
currentVals.setSrmSpeed(prefs.getInt("SRM_Speed"));
currentVals.setSailsFrameCoordinator(prefs
.getBoolean("SAILS_FrameCoordinator"));
currentValues = currentVals;
}

View file

@ -28,7 +28,6 @@ import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.raytheon.uf.common.inventory.exception.DataCubeException;
import com.raytheon.uf.common.dataquery.requests.DbQueryRequest;
import com.raytheon.uf.common.dataquery.requests.DbQueryRequestSet;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
@ -36,6 +35,7 @@ import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest;
import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
import com.raytheon.uf.common.dataquery.responses.DbQueryResponseSet;
import com.raytheon.uf.common.derivparam.library.DerivedParameterGenerator;
import com.raytheon.uf.common.inventory.exception.DataCubeException;
import com.raytheon.uf.common.pointdata.PointDataContainer;
import com.raytheon.uf.common.serialization.comm.RequestRouter;
import com.raytheon.uf.common.status.IUFStatusHandler;
@ -47,6 +47,7 @@ import com.raytheon.uf.common.time.SimulatedTime;
import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.viz.pointdata.util.AbstractPointDataInventory;
import com.raytheon.viz.pointdata.util.PointDataCubeAdapter;
import com.raytheon.viz.radar.frame.RadarDataTime;
/**
*
@ -60,6 +61,9 @@ import com.raytheon.viz.pointdata.util.PointDataCubeAdapter;
* ------------ ---------- ----------- --------------------------
* Oct 8, 2009 bsteffen Initial creation
* Nov 21, 2009 #3576 rjpeter Refactored use of DerivParamDesc.
* May 13, 2015 4461 bsteffen Generate radar times from time queries.
*
*
* </pre>
*
* @author bsteffen
@ -75,6 +79,10 @@ public class RadarDataCubeAdapter extends PointDataCubeAdapter {
private static final String LEVEL_FIELD = "primaryElevationAngle";
private static final String ELEVATION_FIELD = "elevationNumber";
private static final String VOLUME_FIELD = "volumeScanNumber";
@Override
public String[] getSupportedPlugins() {
return new String[] { "radar" };
@ -133,7 +141,14 @@ public class RadarDataCubeAdapter extends PointDataCubeAdapter {
time = new DataTime((Date) map.get(dataTimefield), 0);
} else {
time = (DataTime) map.get(dataTimefield);
time.setLevelValue((Double) map.get(LEVEL_FIELD));
RadarDataTime radarTime = new RadarDataTime(time);
Number level = (Number) map.get(LEVEL_FIELD);
radarTime.setLevelValue(level.doubleValue());
Number elevation = (Number) map.get(ELEVATION_FIELD);
radarTime.setElevationNumber(elevation.intValue());
Number volume = (Number) map.get(VOLUME_FIELD);
radarTime.setVolumeScanNumber(volume.intValue());
time = radarTime;
}
// Best res requests need this because they span a time period
if (time.getRefTime().before(
@ -166,6 +181,8 @@ public class RadarDataCubeAdapter extends PointDataCubeAdapter {
request.addRequestField(dataTimefield, latestOnly);
if (!latestOnly) {
request.addRequestField(LEVEL_FIELD);
request.addRequestField(ELEVATION_FIELD);
request.addRequestField(VOLUME_FIELD);
}
request.setDistinct(true);
return request;

View file

@ -412,7 +412,7 @@ public class TextSegmentCheck implements IQCCheck {
} else {
for (String state : QualityControl.getCountyTypeMap()
.keySet()) {
if (line.contains(state)
if (line.contains(state.toUpperCase())
&& line.contains(QualityControl
.getCountyTypeMap().get(state)
.toUpperCase())) {

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 842 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

View file

@ -112,5 +112,6 @@
indentText="false" />
<contribute xsi:type="menuItem" textLookup="LevelMapping"
key="0BSS" indentText="false" />
<contribute xsi:type="menuItem" textLookup="LevelMapping"
key="NTAT" indentText="false" />
</menuTemplate>

View file

@ -1727,4 +1727,5 @@
<Level displayName="NTAT" key="NTAT" group="S">
<DatabaseLevel levelName="NTAT" levelOneValue="0" />
</Level>
</LevelMappings>

View file

@ -299,7 +299,8 @@ abstract public class AbstractLockingBehavior {
}
pattern.append(")(.*)");
return Pattern.compile(pattern.toString());
return Pattern
.compile(pattern.toString(), Pattern.CASE_INSENSITIVE);
} catch (Exception e) {
statusHandler
.handle(Priority.ERROR,

View file

@ -146,32 +146,38 @@ public class FollowUpLockingBehavior extends AbstractLockingBehavior {
* @return
*/
private String headline(String headline) {
Set<String> notations = new HashSet<String>();
Set<String> names = new HashSet<String>();
for (AffectedAreas affectedArea : affectedAreas) {
if ((affectedArea.getAreaNotation() != null)
&& (affectedArea.getAreaNotation().trim().length() != 0)) {
notations.add(affectedArea.getAreaNotation());
}
if ((affectedArea.getAreasNotation() != null)
&& (affectedArea.getAreasNotation().trim().length() != 0)) {
notations.add(affectedArea.getAreasNotation());
}
if ((affectedArea.getName() != null)
&& (affectedArea.getName().trim().length() != 0)) {
/*
* force area name to upper case for headlines since headlines
* are all upper case
*/
names.add(affectedArea.getName().toUpperCase());
}
}
// Marine products follow different locking rules
if (!isMarineProduct()) {
if (isMarineProduct()) {
// The full headline of a marine product should be locked.
headline = WarnGenPatterns.LOCK_START + headline
+ WarnGenPatterns.LOCK_END;
} else {
Set<String> notations = new HashSet<String>();
Set<String> names = new HashSet<String>();
for (AffectedAreas affectedArea : affectedAreas) {
if ((affectedArea.getAreaNotation() != null)
&& (affectedArea.getAreaNotation().trim().length() != 0)) {
notations.add(affectedArea.getAreaNotation().toUpperCase());
}
if ((affectedArea.getAreasNotation() != null)
&& (affectedArea.getAreasNotation().trim().length() != 0)) {
notations
.add(affectedArea.getAreasNotation().toUpperCase());
}
if ((affectedArea.getName() != null)
&& (affectedArea.getName().trim().length() != 0)) {
/*
* force area name to upper case for headlines since
* headlines are all upper case
*/
names.add(affectedArea.getName().toUpperCase());
}
}
headline = keywords(headline);
Iterator<String> iterator1 = notations.iterator();
while (iterator1.hasNext()) {
@ -192,10 +198,6 @@ public class FollowUpLockingBehavior extends AbstractLockingBehavior {
+ WarnGenPatterns.LOCK_END);
}
}
} else {
// The full headline of a marine product should be locked.
headline = WarnGenPatterns.LOCK_START + headline
+ WarnGenPatterns.LOCK_END;
}
return headline;

View file

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.raytheon.edex.plugin.bufrmos</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -21,7 +21,6 @@ package com.raytheon.edex.plugin.gfe.paraminfo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@ -33,9 +32,6 @@ import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import com.raytheon.uf.common.time.TimeRange;
import com.raytheon.uf.common.time.util.TimeUtil;
/**
*
* Container class to hold a list of metadata pertaining to grid parameters.
@ -48,6 +44,8 @@ import com.raytheon.uf.common.time.util.TimeUtil;
* Jun 24, 2010 #6372 bphillip Initial creation
* Mar 20, 2013 #1774 randerso Added getParmNames,
* changed getAvailableTimes to match A1
* Jul 13, 2015 #4537 randerso Remove getAvailableTimes as it is no longer used
* and cleaned up some interfaces to use List instead of ArrayList
*
* </pre>
*
@ -61,16 +59,16 @@ public class GridParamInfo {
/** The generating processes associated with this model */
@XmlElementWrapper(name = "valtimeMINUSreftime", required = false)
@XmlElement(name = "fcst")
private ArrayList<Integer> times = new ArrayList<Integer>();
private List<Integer> times = new ArrayList<Integer>();
/** List of parameter information */
@XmlElements({ @XmlElement(name = "gridParameterInfo", type = ParameterInfo.class) })
private ArrayList<ParameterInfo> gridParamInfo;
private List<ParameterInfo> gridParamInfo;
/**
* @return the gridParamInfo
*/
public ArrayList<ParameterInfo> getGridParamInfo() {
public List<ParameterInfo> getGridParamInfo() {
return gridParamInfo;
}
@ -78,7 +76,7 @@ public class GridParamInfo {
* @param gridParamInfo
* the gridParamInfo to set
*/
public void setGridParamInfo(ArrayList<ParameterInfo> gridParamInfo) {
public void setGridParamInfo(List<ParameterInfo> gridParamInfo) {
this.gridParamInfo = gridParamInfo;
}
@ -101,7 +99,7 @@ public class GridParamInfo {
/**
* @return the times
*/
public ArrayList<Integer> getTimes() {
public List<Integer> getTimes() {
return times;
}
@ -109,19 +107,10 @@ public class GridParamInfo {
* @param times
* the times to set
*/
public void setTimes(ArrayList<Integer> times) {
public void setTimes(List<Integer> times) {
this.times = times;
}
public List<TimeRange> getAvailableTimes(Date refTime) {
List<TimeRange> availTimes = new ArrayList<TimeRange>(times.size());
for (Integer fcstHour : times) {
availTimes.add(new TimeRange(new Date(refTime.getTime() + fcstHour
* TimeUtil.MILLIS_PER_SECOND), TimeUtil.MILLIS_PER_HOUR));
}
return availTimes;
}
public Collection<String> getParmNames() {
List<ParameterInfo> paramInfoList = this.getGridParamInfo();
Set<String> parmNames = new HashSet<String>();

View file

@ -21,7 +21,6 @@ package com.raytheon.edex.plugin.gfe.paraminfo;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@ -40,7 +39,6 @@ import com.raytheon.uf.common.localization.PathManagerFactory;
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.TimeRange;
import com.raytheon.uf.common.util.mapping.MultipleMappingException;
/**
@ -62,7 +60,7 @@ import com.raytheon.uf.common.util.mapping.MultipleMappingException;
* Apr 30, 2013 1961 bsteffen Add ability to disable grib tables.
* Oct 14, 2013 2473 bsteffen Remove lookup of deprecated grib files.
* Jun 05, 2015 4495 njensen Improved error message
*
* Jul 13, 2015 4537 randerso Removed unused function
*
* </pre>
*
@ -146,14 +144,6 @@ public class GridParamInfoLookup {
return parameterInfo;
}
public List<TimeRange> getParameterTimes(String mappedModel, Date refTime) {
GridParamInfo modelInfo = getGridParamInfo(mappedModel);
if (modelInfo == null) {
return Collections.emptyList();
}
return modelInfo.getAvailableTimes(refTime);
}
public Collection<String> getParmNames(String mappedModel) {
GridParamInfo modelInfo = getGridParamInfo(mappedModel);
if (modelInfo == null) {

View file

@ -51,7 +51,8 @@ import com.raytheon.uf.common.dataquery.db.QueryResult;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.edex.core.EDEXUtil;
import com.raytheon.uf.edex.database.tasks.SqlQueryTask;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.MultiLineString;
@ -65,14 +66,14 @@ import com.vividsolutions.jts.geom.Polygon;
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 18, 2012 #1091 randerso Initial creation
* Mar 28, 2013 #1837 dgilling Change error handling in
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 18, 2012 #1091 randerso Initial creation
* Mar 28, 2013 #1837 dgilling Change error handling in
* getLastUpdated().
* Mar 11, 2014 #2718 randerso Changes for GeoTools 10.5
* 10/16/2014 3454 bphillip Upgrading to Hibernate 4
*
* Mar 11, 2014 #2718 randerso Changes for GeoTools 10.5
* Oct 16, 2014 3454 bphillip Upgrading to Hibernate 4
* Jul 13, 2015 4500 rjpeter Fix SQL Injection concerns.
* </pre>
*
* @author randerso
@ -105,7 +106,7 @@ public class DbShapeSource {
private String instanceName;
private String tableName;
private final String tableName;
private List<String> attributeNames;
@ -447,14 +448,13 @@ public class DbShapeSource {
public Date getLastUpdated() throws MissingLocalMapsException {
String sqlQuery = "SELECT import_time FROM " + SCHEMA_NAME
+ ".map_version WHERE table_name = '" + this.tableName + "';";
+ ".map_version WHERE table_name = :tableName";
try {
SqlQueryTask task = new SqlQueryTask(sqlQuery, DB_NAME);
QueryResult result = task.execute();
CoreDao dao = new CoreDao(DaoConfig.forDatabase(DB_NAME));
QueryResult result = dao.executeMappedSQLQuery(sqlQuery,
"tableName", this.tableName);
return (Date) result.getRowColumnValue(0, 0);
} catch (Exception e) {
// statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(),
// e);
throw new MissingLocalMapsException(e);
}
}

View file

@ -119,6 +119,7 @@ import com.raytheon.uf.edex.database.DataAccessLayerException;
* 09/09/2014 #3356 njensen Remove CommunicationException
* 03/05/2015 #4169 randerso Fix error handling in getDatabase
* 06/29/2015 #4537 rferrel Allow for durations less then 1 hour.
* 07/13/2015 #4537 randerso Additional changes to allow D2DParms with sub-hourly durations/intervals
*
* </pre>
*
@ -318,7 +319,7 @@ public class D2DGridDatabase extends VGridDatabase {
private GridParamInfo modelInfo;
private List<TimeRange> availableTimes;
private List<Long> availableTimes;
private GFED2DDao d2dDao;
@ -370,7 +371,12 @@ public class D2DGridDatabase extends VGridDatabase {
throw new GfeException("No model info for: " + d2dModelName);
}
this.availableTimes = modelInfo.getAvailableTimes(refTime);
List<Integer> fcstHours = modelInfo.getTimes();
this.availableTimes = new ArrayList<>(fcstHours.size());
for (int fcstHour : fcstHours) {
this.availableTimes.add(refTime.getTime()
+ (fcstHour * TimeUtil.MILLIS_PER_SECOND));
}
// Get the database id for this database.
this.valid = this.dbId.isValid();
@ -461,19 +467,20 @@ public class D2DGridDatabase extends VGridDatabase {
List<Integer> forecastTimes = this.modelInfo.getTimes();
possibleInventorySlots = new HashMap<Integer, TimeRange>(
forecastTimes.size(), 1.0f);
long millisDur = tc.getDuration() * TimeUtil.MILLIS_PER_SECOND;
if (accParm) {
long millisDur = tc.getDuration() * TimeUtil.MILLIS_PER_SECOND;
// adjust accumulative parms to have forecast hour
// at end of time range
for (int i = 0; i < forecastTimes.size(); i++) {
possibleInventorySlots.put(forecastTimes.get(i), new TimeRange(
new Date(availableTimes.get(i).getStart().getTime()
- millisDur), millisDur));
possibleInventorySlots.put(forecastTimes.get(i),
new TimeRange(availableTimes.get(i) - millisDur,
availableTimes.get(i)));
}
} else if ((GridPathProvider.STATIC_PARAMETERS.contains(atts
.getShort_name())) && !availableTimes.isEmpty()) {
TimeRange ntr = availableTimes.get(0).combineWith(
availableTimes.get(availableTimes.size() - 1));
TimeRange ntr = new TimeRange(availableTimes.get(0),
availableTimes.get(availableTimes.size() - 1)
+ TimeUtil.MILLIS_PER_HOUR);
// make static parms have a single time range that spans
// all availableTimes
for (int i = 0; i < forecastTimes.size(); i++) {
@ -481,8 +488,9 @@ public class D2DGridDatabase extends VGridDatabase {
}
} else {
for (int i = 0; i < forecastTimes.size(); i++) {
possibleInventorySlots.put(forecastTimes.get(i),
availableTimes.get(i));
TimeRange timeRange = new TimeRange(availableTimes.get(i),
availableTimes.get(i) + millisDur);
possibleInventorySlots.put(forecastTimes.get(i), timeRange);
}
}
@ -525,9 +533,11 @@ public class D2DGridDatabase extends VGridDatabase {
List<Integer> forecastTimes = this.modelInfo.getTimes();
Map<Integer, TimeRange> possibleInventorySlots = new HashMap<Integer, TimeRange>(
forecastTimes.size(), 1.0f);
long millisDur = tc.getDuration() * TimeUtil.MILLIS_PER_SECOND;
for (int i = 0; i < forecastTimes.size(); i++) {
possibleInventorySlots.put(forecastTimes.get(i),
availableTimes.get(i));
TimeRange timeRange = new TimeRange(availableTimes.get(i),
availableTimes.get(i) + millisDur);
possibleInventorySlots.put(forecastTimes.get(i), timeRange);
}
String uGfeParmName = uatts.getShort_name();
@ -1078,22 +1088,20 @@ public class D2DGridDatabase extends VGridDatabase {
* The times
* @return The time constraints
*/
private TimeConstraints getTimeConstraints(List<TimeRange> times) {
private TimeConstraints getTimeConstraints(List<Long> times) {
if (times.size() <= 1) {
return new TimeConstraints(TimeUtil.SECONDS_PER_HOUR,
TimeUtil.SECONDS_PER_HOUR, 0);
}
long repeat = (times.get(1).getStart().getTime() - times.get(0)
.getStart().getTime())
long repeat = (times.get(1) - times.get(0))
/ TimeUtil.MILLIS_PER_SECOND;
long start = (times.get(0).getStart().getTime() / TimeUtil.MILLIS_PER_SECOND)
long start = (times.get(0) / TimeUtil.MILLIS_PER_SECOND)
% TimeUtil.SECONDS_PER_DAY;
for (int i = 1; i < (times.size() - 1); i++) {
if (((times.get(i + 1).getStart().getTime() - times.get(i)
.getStart().getTime()) / TimeUtil.MILLIS_PER_SECOND) != repeat) {
if (((times.get(i + 1) - times.get(i)) / TimeUtil.MILLIS_PER_SECOND) != repeat) {
return new TimeConstraints(TimeUtil.SECONDS_PER_HOUR,
TimeUtil.SECONDS_PER_HOUR, 0);
}

View file

@ -46,7 +46,8 @@ import com.raytheon.uf.common.python.PythonScript;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.util.FileUtil;
import com.raytheon.uf.edex.database.tasks.SqlQueryTask;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
/**
* Code to generate the AreaDictionary for text formatters
@ -63,7 +64,7 @@ import com.raytheon.uf.edex.database.tasks.SqlQueryTask;
* python modules from the GIS database tables
* Dec 08, 2014 #4953 randerso Updated Jep include path to allow use of
* LocalizationSupport
*
* Jul 13, 2015 4500 rjpeter Fix SQL Injection concerns.
* </pre>
*
* @author wldougher
@ -77,14 +78,14 @@ public class AreaDictionaryMaker {
protected static final String FIPS_CITY_QUERY = //
"SELECT name, population, ST_Y(city.the_geom), ST_X(city.the_geom) "
+ "FROM mapdata.city, mapdata.county "
+ "WHERE county.state = '%1$s' AND substring(fips,3,3) = '%2$s' "
+ "WHERE county.state = :state AND substring(fips,3,3) = :num "
+ "AND ST_Contains(county.the_geom, city.the_geom) "
+ "ORDER BY city.name;";
protected static final String ZONES_CITY_QUERY = //
"SELECT city.name, population, ST_Y(city.the_geom), ST_X(city.the_geom) "
+ "FROM mapdata.city, mapdata.zone "
+ "WHERE zone.state = '%1$s' AND zone.zone = '%2$s' "
+ "WHERE zone.state = :state AND zone.zone = :num "
+ "AND ST_Contains(zone.the_geom, city.the_geom) "
+ "ORDER BY city.name;";
@ -320,6 +321,7 @@ public class AreaDictionaryMaker {
StringBuilder sb = new StringBuilder();
Pattern pattern = Pattern.compile("(\\p{Upper}{2})" + separator
+ "(\\d{3})");
CoreDao dao = new CoreDao(DaoConfig.forDatabase("maps"));
for (Map<String, Object> att : attributes) {
String ean = (String) att.get("editarea");
@ -338,14 +340,15 @@ public class AreaDictionaryMaker {
String fullStateName = this.stateDict.get(state);
String partOfState = PART_OF_STATE.get(att.get("fe_area"));
String wfo = (String) att.get("cwa");
SqlQueryTask task = new SqlQueryTask(String.format(
cityQuery, state, num), "maps");
Map<String, Object> paramMap = new HashMap<>(2, 1);
paramMap.put("state", state);
paramMap.put("num", num);
// retrieve cities for this area
QueryResult citiesResult = null;
try {
citiesResult = task.execute();
citiesResult = dao.executeMappedSQLQuery(cityQuery,
paramMap);
} catch (Exception e) {
statusHandler
.error("Error getting cites for " + ean, e);
@ -407,10 +410,10 @@ public class AreaDictionaryMaker {
}
private void genStateDict() {
SqlQueryTask task = new SqlQueryTask(
"SELECT state, name FROM mapdata.states", "maps");
try {
QueryResult result = task.execute();
CoreDao dao = new CoreDao(DaoConfig.forDatabase("maps"));
QueryResult result = dao
.executeMappedSQLQuery("SELECT state, name FROM mapdata.states");
stateDict = new HashMap<String, String>(result.getResultCount(),
1.0f);
for (QueryResultRow row : result.getRows()) {

View file

@ -50,7 +50,8 @@ import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.util.FileUtil;
import com.raytheon.uf.edex.database.cluster.ClusterLockUtils;
import com.raytheon.uf.edex.database.cluster.ClusterTask;
import com.raytheon.uf.edex.database.tasks.SqlQueryTask;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
/**
* Generate and configure text products when needed.
@ -74,7 +75,7 @@ import com.raytheon.uf.edex.database.tasks.SqlQueryTask;
* Cleaned up how protected file updates are returned
* Jan 23, 2015 #4027 randerso Fixed python include path
* Apr 27, 2015 4259 njensen Updated for new JEP API
*
* Jul 13, 2015 4500 rjpeter Removed SqlQueryTask.
* </pre>
*
* @author jelkins
@ -210,8 +211,8 @@ public class Configurator {
lf = pathMgr.getLocalizationFile(context,
FileUtil.join("python", "gfe", "SiteCFG.py"));
SqlQueryTask task = new SqlQueryTask(CWA_QUERY, "maps");
QueryResult results = task.execute();
CoreDao dao = new CoreDao(DaoConfig.forDatabase("maps"));
QueryResult results = dao.executeMappedSQLQuery(CWA_QUERY);
try (PrintWriter out = new PrintWriter(lf.openOutputStream())) {
out.println("##");
out.println("# Contains information about products, regions, etc. for each site");

View file

@ -209,7 +209,7 @@ def advection(windGrid, scalarGrid):
# in any SmartTool.
def getLatLonGrids(gridLoc):
# Fetch the grids
latLonGrid = gridLoc.getLatLonGrid().__numpy__[0];
latLonGrid = gridLoc.getLatLonGrid()
latLonGrid = reshape(latLonGrid, (2,gridLoc.getNy().intValue(),gridLoc.getNx().intValue()), order='F')
return latLonGrid[1], latLonGrid[0]

View file

@ -370,7 +370,7 @@ def storeLatLonGrids(client, file, databaseID, invMask, krunch, clipArea):
gridLoc = IFPServerConfigManager.getServerConfig(DatabaseID(databaseID).getSiteId()).dbDomain()
pDict = gridLoc.getProjection()
latLonGrid = gridLoc.getLatLonGrid().getNDArray()
latLonGrid = gridLoc.getLatLonGrid()
latLonGrid = numpy.reshape(latLonGrid, (2,gridLoc.getNy().intValue(),gridLoc.getNx().intValue()), order='F')
@ -1270,10 +1270,9 @@ def main(outputFilename, parmList, databaseID, startTime,
# AFPS.DBSubsystem_getBuiltBy(), AFPS.DBSubsystem_getBuiltOn(),
# AFPS.DBSubsystem_getBuildVersion())
try:
len(parmList)
except TypeError:
if hasattr(parmList, 'java_name'):
parmList = JUtil.javaObjToPyVal(parmList)
argDict = {"outputFilename": outputFilename,
"parmList": parmList,
"databaseID": databaseID,

View file

@ -496,4 +496,7 @@
<Level key="BSS">
<DatabaseLevel levelName="BSS" levelOneValue="0.0"/>
</Level>
<Level key="NTAT">
<DatabaseLevel levelName="NTAT" levelOneValue="0.0"/>
</Level>
</LevelMappings>

View file

@ -329,7 +329,7 @@
<gridParameterInfo xsi:type="parameterInfo">
<short_name>cicep</short_name>
<long_name>Categorical ice pellets</long_name>
<units>yes=1, no=0</units>
<units>yn</units>
<udunits />
<uiname>CategoricalIcePlt</uiname>
<valid_range>0.0</valid_range>
@ -357,7 +357,7 @@
<gridParameterInfo xsi:type="parameterInfo">
<short_name>crain</short_name>
<long_name>Categorical rain</long_name>
<units>yes=1, no=0</units>
<units>yn</units>
<udunits />
<uiname>CategoricalRain</uiname>
<valid_range>0.0</valid_range>
@ -457,7 +457,7 @@
<gridParameterInfo xsi:type="parameterInfo">
<short_name>dswrf</short_name>
<long_name>Downward shortwave radiation flux</long_name>
<units>W/m2</units>
<units>W/m**2</units>
<udunits>watts/meter2</udunits>
<n3D>0</n3D>
<levelsDesc>SFC</levelsDesc>
@ -468,7 +468,7 @@
<gridParameterInfo xsi:type="parameterInfo">
<short_name>heli</short_name>
<long_name>helicity sigma</long_name>
<units>m/s2</units>
<units>m/s**2</units>
<udunits>meter/second2</udunits>
<uiname>hel</uiname>
<valid_range>0.0</valid_range>
@ -599,7 +599,7 @@
<gridParameterInfo xsi:type="parameterInfo">
<short_name>pr</short_name>
<long_name>precipitation rate</long_name>
<units>Kg/m**2 / s</units>
<units>(kg/m**2)/s</units>
<valid_range>0.0</valid_range>
<valid_range>0.10000000149</valid_range>
<fillValue>-99999.0</fillValue>
@ -627,7 +627,7 @@
<gridParameterInfo xsi:type="parameterInfo">
<short_name>cfrzr</short_name>
<long_name>Categorical freezing rain</long_name>
<units>yes=1, no=0</units>
<units>yn</units>
<udunits />
<uiname>CategoricalFrzRain</uiname>
<valid_range>0.0</valid_range>
@ -642,7 +642,7 @@
<gridParameterInfo xsi:type="parameterInfo">
<short_name>wd</short_name>
<long_name>Wind Direction</long_name>
<units>degreeTrue</units>
<units>degree_angle</units>
<udunits>degree_True</udunits>
<uiname>windDir</uiname>
<valid_range>0.0</valid_range>

View file

@ -26,6 +26,7 @@
# 05/07/2015 4027 randerso Migrated A1 OB9.16 code to A2
# 06/17/2015 4027 dgilling Perform case-insensitive
# comparisons in foundCTAs.
# 07/13/2015 4648 randerso Fix bullets in follow up products
#
#-------------------------------------------------------------------------
# Description: This product is a template for creating Hazard Products.
@ -707,21 +708,21 @@ class TextProduct(TextRules.TextRules, SampleAnalysis.SampleAnalysis,
print "newBullets = ", newBullets
print "segment text is: ", segmentText
for bullet in newBullets:
if not "* " + bullet + "..." in segmentText:
if re.search("\* " + bullet + "\.\.\.", segmentText, flags=re.IGNORECASE) is None:
print bullet + " not in segmentText"
start = self._bulletOrder().index(bullet) + 1
end = len(self._bulletOrder())
bulletFlag = 1
for i in range(start,end):
if "* " + self._bulletOrder()[i] + "..." in segmentText and bulletFlag:
if (re.search("\* " + self._bulletOrder()[i] + "\.\.\.", segmentText, flags=re.IGNORECASE) is not None) and bulletFlag:
print "* " + self._bulletOrder()[i] + "... found!"
segmentTextSplit = string.split(segmentText,"* " + self._bulletOrder()[i] + "...")
segmentTextSplit = re.split("\* " + self._bulletOrder()[i] + "\.\.\.", segmentText, flags=re.IGNORECASE)
segmentText = string.join(segmentTextSplit,"* " + bullet + \
"...|* Enter bullet text *|\n\n* " + self._bulletOrder()[i] + "...")
bulletFlag = 0
if bulletFlag:
print "appending to bottom list of bullets!"
segmentTextSplit = string.split(segmentText,"Precautionary/preparedness actions...")
segmentTextSplit = re.split("Precautionary/preparedness actions\.\.\.", segmentText, flags=re.IGNORECASE)
segmentText = "\n" + string.join(segmentTextSplit,"* " + bullet + \
"...|* Enter bullet text *|\n\nPrecautionary/preparedness actions...")
bulletFlag = 0
@ -751,14 +752,14 @@ class TextProduct(TextRules.TextRules, SampleAnalysis.SampleAnalysis,
print "hazardBodyText info: removeBulletList: ",removeBulletList
# Finally remove the bullets no longer needed.
for bullet in removeBulletList:
if string.find(segmentText,"* "+ bullet + "...") != -1:
segmentTextSplit = string.split(segmentText,"* " + bullet + "...")
if re.search("\* "+ bullet + "\.\.\.", segmentText, flags=re.IGNORECASE) is not None:
segmentTextSplit = re.split("\* " + bullet + "\.\.\.", segmentText, flags=re.IGNORECASE)
print "segmentTextSplit is ", segmentTextSplit
segmentTextSplit2 = string.split(segmentTextSplit[1],"*",1)
if len(segmentTextSplit2) == 2:
segmentTextSplit[1] = "*" + segmentTextSplit2[1]
else:
segmentTextSplit2 = string.split(segmentTextSplit[1],"Precautionary/preparedness actions...",1)
segmentTextSplit2 = re.split("Precautionary/preparedness actions\.\.\.", segmentTextSplit[1], 1, flags=re.IGNORECASE)
if len(segmentTextSplit2) == 2:
segmentTextSplit[1] = "Precautionary/preparedness actions..." + segmentTextSplit2[1]
segmentText = string.join(segmentTextSplit,"")

View file

@ -23,10 +23,13 @@ package com.raytheon.edex.plugin.radar.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import com.raytheon.uf.common.dataplugin.radar.RadarStation;
import com.raytheon.uf.common.dataquery.db.QueryResult;
@ -46,9 +49,9 @@ import com.vividsolutions.jts.geom.Coordinate;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 7/24/07 353 bphillip Initial Check in
* 10/16/2014 3454 bphillip Upgrading to Hibernate 4
* 10/16/2014 3454 bphillip Upgrading to Hibernate 4
* 10/28/2014 3454 bphillip Fix usage of getSession()
*
* Jul 09, 2015 4500 rjpeter Add setSridOnAllRadarStation.
* </pre>
*
* @author bphillip
@ -108,7 +111,7 @@ public class RadarStationDao extends CoreDao {
public List<RadarStation> queryByWfo(String wfo)
throws DataAccessLayerException {
List<?> stations = queryBySingleCriteria("wfoId", wfo);
if (stations == null || stations.isEmpty()) {
if ((stations == null) || stations.isEmpty()) {
return null;
} else {
return (List<RadarStation>) stations;
@ -162,11 +165,11 @@ public class RadarStationDao extends CoreDao {
DetachedCriteria crit = DetachedCriteria
.forClass(RadarStation.class);
Disjunction stationEq = Expression.disjunction();
for (int i = 0; i < names.length; i++) {
if (((Object[]) names[i])[0] != null) {
stationEq.add(Expression.eq("wfoId",
((Object[]) names[i])[0].toString()));
Disjunction stationEq = Restrictions.disjunction();
for (Object name : names) {
if (((Object[]) name)[0] != null) {
stationEq.add(Restrictions.eq("wfoId",
((Object[]) name)[0].toString()));
}
}
crit.add(stationEq);
@ -174,7 +177,7 @@ public class RadarStationDao extends CoreDao {
try {
return crit.getExecutableCriteria(session).list();
} finally {
if (session != null){
if (session != null) {
session.close();
}
}
@ -221,4 +224,20 @@ public class RadarStationDao extends CoreDao {
return rdaIds;
}
/**
* Sets the station field on all radar spatial entries to setsrid of the
* geometry.
*/
public void setSridOnAllRadarStation() {
txTemplate.execute(new TransactionCallback<Integer>() {
@Override
public Integer doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
SQLQuery query = sess
.createSQLQuery("update radar_spatial set station=st_setsrid(the_geom, 4326)");
return query.executeUpdate();
}
});
}
}

View file

@ -25,7 +25,6 @@ import com.raytheon.uf.common.localization.PathManagerFactory;
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.edex.database.DataAccessLayerException;
import com.raytheon.uf.edex.ndm.ingest.INationalDatasetSubscriber;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
@ -40,13 +39,12 @@ import com.vividsolutions.jts.io.WKTReader;
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 10Oct2011 10520 JWork Initial check-in.
* 10Oct2011 10520 JWork Initial check-in.
* 09/11/2012 DR 15366 D. Friedman Set SRID on radar stations.
* Mar 06, 2014 2876 mpduff Moved NationalDatasetSubscriber.
* Mar 06, 2014 2876 mpduff Moved NationalDatasetSubscriber.
* Jul 09, 2015 4500 rjpeter Fix SQL Injection concern.
* </pre>
*
*/
public class Import88DLocationsUtil implements INationalDatasetSubscriber {
private static final IUFStatusHandler statusHandler = UFStatus
.getHandler(Import88DLocationsUtil.class);
@ -292,11 +290,10 @@ public class Import88DLocationsUtil implements INationalDatasetSubscriber {
* Once GetTools is updated/fixed, this should be removed.
*/
try {
radarStationDAO
.executeNativeSql("update radar_spatial set the_geom=st_setsrid(the_geom, 4326)");
} catch (DataAccessLayerException e) {
radarStationDAO.setSridOnAllRadarStation();
} catch (Exception e) {
statusHandler.handle(Priority.ERROR,
"Failed to update the SRIDs in the radar_spatial_table", e);
"Failed to update the SRIDs in the radar_spatial table", e);
}
if (statusHandler.isPriorityEnabled(Priority.INFO)) {

View file

@ -28,6 +28,8 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import com.raytheon.uf.common.localization.IPathManager;
import com.raytheon.uf.common.localization.LocalizationContext;
@ -37,7 +39,8 @@ import com.raytheon.uf.common.localization.PathManagerFactory;
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.edex.database.tasks.SqlStatementTask;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
import com.raytheon.uf.edex.ndm.ingest.INationalDatasetSubscriber;
/**
@ -51,7 +54,7 @@ import com.raytheon.uf.edex.ndm.ingest.INationalDatasetSubscriber;
* ------------ ---------- ----------- --------------------------
* Apr 11, 2011 bfarmer Initial creation
* Mar 06, 2014 2876 mpduff New NDM plugin.
*
* Jul 13, 2015 4500 rjpeter Fix SQL Injection concerns.
* </pre>
*
* @author bfarmer
@ -137,24 +140,17 @@ public class MarineInfoSubscriber implements INationalDatasetSubscriber {
if ((outFile != null) && outFile.exists()) {
BufferedReader fis = null;
try {
CoreDao dao = new CoreDao(DaoConfig.forDatabase("maps"));
fis = new BufferedReader(new InputStreamReader(
new FileInputStream(outFile)));
try {
SqlStatementTask task = new SqlStatementTask(setupOne,
"maps");
task.execute();
task = new SqlStatementTask(setupTwo, "maps");
task.execute();
task = new SqlStatementTask(setupThree, "maps");
task.execute();
task = new SqlStatementTask(setupFour, "maps");
task.execute();
task = new SqlStatementTask(setupFive, "maps");
task.execute();
task = new SqlStatementTask(setupSix, "maps");
task.execute();
task = new SqlStatementTask(setupSeven, "maps");
task.execute();
dao.executeSQLUpdate(setupOne);
dao.executeSQLUpdate(setupTwo);
dao.executeSQLUpdate(setupThree);
dao.executeSQLUpdate(setupFour);
dao.executeSQLUpdate(setupFive);
dao.executeSQLUpdate(setupSix);
dao.executeSQLUpdate(setupSeven);
} catch (Exception e) {
statusHandler.handle(Priority.CRITICAL,
"Error resetting the MarineInfo DB table, ", e);
@ -163,7 +159,8 @@ public class MarineInfoSubscriber implements INationalDatasetSubscriber {
String line = null;
String[] splitOne = null;
String[] splitTwo = null;
StringBuilder query = null;
StringBuilder query = new StringBuilder();
Map<String, Object> paramMap = new HashMap<>(8, 1);
try {
while ((line = fis.readLine()) != null) {
splitOne = line.split("\\s+", 5);
@ -176,27 +173,21 @@ public class MarineInfoSubscriber implements INationalDatasetSubscriber {
// "INSERT INTO" + DBSCHEMA + "." + DBTABLE
// "(st, name, prog_disc, warngenlev,the_geom) "
// "VALUES('3','4',2,5,GeomFromText('POINT(1, 0)', 4326));"
query = new StringBuilder("INSERT INTO \"");
query.setLength(0);
query.append("INSERT INTO \"");
query.append(DBSCHEMA);
query.append("\".\"");
query.append(DBTABLE);
query.append("\"(st, name, prog_disc, warngenlev, the_geom) VALUES('");
query.append(splitOne[3]); // st
query.append("', '");
query.append(splitTwo[0]); // name
query.append("', ");
query.append(splitOne[2]); // prog_disc
query.append(", ");
query.append(splitTwo[1]); // warngenlev
query.append(", ");
query.append("GeomFromText('POINT(");
query.append(splitOne[1]); // the_geom 1
query.append(" ");
query.append(splitOne[0]); // the_geom 2
query.append(")', 4326));"); // End query
SqlStatementTask task = new SqlStatementTask(
query.toString(), "maps");
task.execute();
query.append("\"(st, name, prog_disc, warngenlev, the_geom) VALUES(");
query.append(":st, :name, :prog_disc, :warngenlev, ");
query.append("GeomFromText('POINT(:geom1, :geom2)', 4326))");
paramMap.put("st", splitOne[3]);
paramMap.put("name", splitTwo[0]);
paramMap.put("prog_disc", splitOne[2]);
paramMap.put("warngenlev", splitTwo[1]);
paramMap.put("geom1", splitOne[1]);
paramMap.put("geom2", splitOne[0]);
dao.executeSQLUpdate(query.toString(), paramMap);
}
} catch (IOException e) {
statusHandler.handle(Priority.PROBLEM,

View file

@ -1,131 +0,0 @@
#
# GempakGridNavigationRequest
#
# This code has been developed by the SIB for use in the AWIPS2 system.
# Performs a BaseRequest for a grid navigation parameters from GEMPAK.
#
# Usage:
# import GempakGridNavigationRequest
# dataRequest = GempakGridNavigationRequest.GempakGridNavigationRequest()
# dataRequest.setGridId("...")
# return dataRequest.execute()
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 06/02/10 173_partC mgamazaychikov Initial Creation
# 02/02/11 mli add eventName for dynamic model names
#
import BaseRequest
from java.util import ArrayList
from com.raytheon.uf.common.message.response import ResponseMessageGeneric
from com.raytheon.edex.uengine.tasks.query import SqlQueryTask
from gov.noaa.nws.ncep.edex.uengine.utility import GempakConvert
class GempakGridNavigationRequest(BaseRequest.BaseRequest):
def __init__(self, pluginName='grib'):
self.eventName = None
self.pluginName = pluginName
if self.pluginName == 'grib':
self.tableName = 'grib_models'
elif self.pluginName == 'ncgrib':
self.tableName = 'ncgrib_models'
BaseRequest.BaseRequest.__init__(self, self.pluginName)
#
# Sets the ICAO parameter for the query
#
def setGridIdParms(self, aGridName, *parms):
for ii in range(len(parms)):
if ii == 0:
#print "setting time to", parms[0]
convert = GempakConvert()
self.query.addParameter("dataTime", convert.dattimToDbtime(parms[0]))
elif ii == 1:
#print "setting eventName to", parms[1]
self.query.addParameter("modelInfo.eventName", parms[1])
self.gridName= aGridName
#
# Execute the BaseRequest and calls the appropriate response function
#
def execute(self):
#
# set up the db query for grib plugin
#
if self.pluginName == 'grib':
#
# Construct the SQL query to retrieve record IDs from bufrua table
#
gridIdQueryHead = "SELECT DISTINCT id FROM " + self.tableName + " WHERE modelname='"
gridIdQueryTail = "'"
gridIdQuery = gridIdQueryHead + self.gridName + gridIdQueryTail
#
#
# Create an instance of SQL Query and execute it
#
self.sqlGridIDQuery = SqlQueryTask(gridIdQuery)
sqlGridIDQueryResults = self.sqlGridIDQuery.execute()
#
# Retrieve the rows into the ArrayList of grid IDs
#
gridID = ArrayList()
gridID = sqlGridIDQueryResults.getRows()
gridIDList = ArrayList()
for gid in gridID:
strID = "%s" % gid
gridIDList.add(strID[1:-1])
szID = gridIDList.size()
if szID == 0:
return self.makeNullResponse()
singleGridId = gridIDList.get(0)
self.query.setCount(1)
modelInfoId = "%s" % singleGridId
#print "modelInfoId=", modelInfoId
self.query.addParameter("modelInfo.id","%s" % singleGridId)
#
# set up the db query for ncgrib plugin
#
elif self.pluginName == 'ncgrib':
self.query.addParameter("modelInfo.modelName","%s" % self.gridName)
# if (self.eventName != None):
# self.query.addParameter("modelInfo.eventName","%s" % self.eventName)
self.query.setCount(1)
#
# execute the query
#
self.queryResults = self.query.execute()
if self.queryResults is None or self.queryResults.size() == 0:
self.makeNullResponse()
else:
return self.__makeResponse()
#
# Builds the return string content and adds it to the response ArrayList
#
def __makeResponse(self):
from com.raytheon.edex.uengine.tasks.decode import FileIn
response = ArrayList()
size = self.queryResults.size()
for i in range(size):
currentQuery = self.queryResults.get(i)
if self.pluginName == 'grib':
content = GempakConvert.getGridNavigationContent(currentQuery.getSpatialObject())
elif self.pluginName == 'ncgrib':
content = GempakConvert.getNcgridNavigationContent(currentQuery.getSpatialObject())
response.add(ResponseMessageGeneric(content))
return response
#
# Returns a string with null response
#
def makeNullResponse(self):
response = ArrayList()
response.add(ResponseMessageGeneric("Database Query returned no results"))
return response

View file

@ -18,14 +18,13 @@
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 12/22/09 173_partB mgamazaychikov Initial Creation
# 07/13/15 4500 rjpeter Remove SqlQueryTask
#
import BaseRequest
from com.raytheon.uf.common.message.response import ResponseMessageGeneric
from java.util import ArrayList
from gov.noaa.nws.ncep.edex.uengine.utility import GempakConvert
from com.raytheon.edex.uengine.tasks.query import SqlQueryTask
class GempakMcidasHdrRequest(BaseRequest.BaseRequest):

View file

@ -1,96 +0,0 @@
#
# GempakNcgridNavigationRequest
#
# This code has been developed by the SIB for use in the AWIPS2 system.
# Performs a BaseRequest for a grid navigation parameters from GEMPAK.
#
# Usage:
# import GempakNcgridNavigationRequest
# dataRequest = GempakNcgridNavigationRequest.GempakNcgridNavigationRequest()
# dataRequest.setGridId("...")
# return dataRequest.execute()
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 06/02/10 173_partC mgamazaychikov Initial Creation
#
import BaseRequest
from java.util import ArrayList
from com.raytheon.uf.common.message.response import ResponseMessageGeneric
from com.raytheon.edex.uengine.tasks.query import SqlQueryTask
from gov.noaa.nws.ncep.edex.uengine.utility import GempakConvert
class GempakNcgridNavigationRequest(BaseRequest.BaseRequest):
def __init__(self):
BaseRequest.BaseRequest.__init__(self, "ncgrib")
#
# Sets the ICAO parameter for the query
#
def setGridId(self, aGridName):
self.gridName= aGridName
#
# Execute the BaseRequest and calls the appropriate response function
#
def execute(self):
#
# Construct the SQL query to retrieve record IDs from bufrua table
#
gridIdQueryHead = "SELECT DISTINCT id FROM ncgrib_models WHERE modelname='"
gridIdQueryTail = "'"
gridIdQuery = gridIdQueryHead + self.gridName + gridIdQueryTail
#
#
# Create an instance of SQL Query and execute it
#
self.sqlGridIDQuery = SqlQueryTask(gridIdQuery)
sqlGridIDQueryResults = self.sqlGridIDQuery.execute()
#
# Retrieve the rows into the ArrayList of grid IDs
#
gridID = ArrayList()
gridID = sqlGridIDQueryResults.getRows()
gridIDList = ArrayList()
for gid in gridID:
strID = "%s" % gid
gridIDList.add(strID[1:-1])
szID = gridIDList.size()
if szID == 0:
return self.makeNullResponse()
singleGridId = gridIDList.get(0)
self.query.setCount(1)
modelInfoId = "%s" % singleGridId
self.query.addParameter("modelInfo.id","%s" % singleGridId)
self.queryResults = self.query.execute()
if self.queryResults is None or self.queryResults.size() == 0:
self.makeNullResponse()
else:
return self.__makeResponse()
#
# Builds the return string content and adds it to the response ArrayList
#
def __makeResponse(self):
from com.raytheon.edex.uengine.tasks.decode import FileIn
response = ArrayList()
size = self.queryResults.size()
for i in range(size):
currentQuery = self.queryResults.get(i)
content = GempakConvert.getNcgridNavigationContent(currentQuery.getSpatialObject())
response.add(ResponseMessageGeneric(content))
return response
#
# Returns a string with null response
#
def makeNullResponse(self):
response = ArrayList()
response.add(ResponseMessageGeneric("Database Query returned no results"))
return response

View file

@ -18,10 +18,12 @@
# ------------ ---------- ----------- --------------------------
# 06/02/10 173_partC mgamazaychikov Initial Creation.
# 09/09/10 mgamazaychikov Added setSeparator function
# 07/13/15 4500 rjpeter Remove SqlQueryTask
#
from com.raytheon.uf.common.message.response import ResponseMessageGeneric
from com.raytheon.uf.common.dataquery.db import QueryResult
from com.raytheon.uf.edex.database.tasks import SqlQueryTask
from com.raytheon.uf.edex.database.dao import CoreDao
from com.raytheon.uf.edex.database.dao import DaoConfig
from java.util import ArrayList
class GempakSqlQuery():
@ -87,11 +89,8 @@ class GempakSqlQuery():
def execute(self):
#self.queryResults = ArrayList()
#
# Create an instance of SQL Query and execute it
#
self.sqlQuery = SqlQueryTask(self.query, self.dbname)
self.queryResults = self.sqlQuery.execute()
dao = CoreDao(DaoConfig.forDatabase(self.dbname))
self.queryResults = dao.executeMappedSQLQuery(self.query)
#
# Make response based on the query results

View file

@ -1,46 +0,0 @@
##
# 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.
##
from com.raytheon.uf.edex.database.tasks import HqlQueryTask
from com.raytheon.uf.common.message.response import ResponseMessageGeneric
from java.util import ArrayList
#
# Generalized query script for querying arbitrary rows out of any table in any database
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 10/16/08 #1615 bphillip Initial Creation.
#
#
class HqlQuery():
def __init__(self, hqlQuery, dbName="metadata"):
self.__query = HqlQueryTask(hqlQuery, dbName)
def execute(self):
queryResults = self.__query.execute()
response = ArrayList()
response.add(ResponseMessageGeneric(queryResults))
return response

View file

@ -1,46 +0,0 @@
##
# 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.
##
from com.raytheon.uf.edex.database.tasks import HqlStatementTask
from com.raytheon.uf.common.message.response import ResponseMessageGeneric
from java.util import ArrayList
#
# Generalized query script for executing non query type hql statements
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 10/21/08 #1615 bphillip Initial Creation.
#
#
class HqlStatement():
def __init__(self, hqlQuery,dbName="metadata"):
self.__stmt = HqlStatementTask(hqlQuery,dbName)
def execute(self):
result = self.__stmt.execute()
response = ArrayList()
response.add(ResponseMessageGeneric(result))
return response

View file

@ -18,7 +18,8 @@
# further licensing information.
##
from com.raytheon.uf.edex.database.tasks import SqlQueryTask
from com.raytheon.uf.edex.database.dao import CoreDao
from com.raytheon.uf.edex.database.dao import DaoConfig
from com.raytheon.uf.common.message.response import ResponseMessageGeneric
from java.util import ArrayList
@ -30,17 +31,19 @@ from java.util import ArrayList
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 10/16/08 #1615 bphillip Initial Creation.
#
# 10/16/08 #1615 bphillip Initial Creation.
# 07/13/15 4500 rjpeter Remove SqlQueryTask.
#
class SqlQuery():
def __init__(self, sqlQuery,dbName="metadata"):
self.__query = SqlQueryTask(sqlQuery,dbName)
self.__query = sqlQuery
self.__dbName = dbName
def execute(self):
queryResults = self.__query.execute()
dao = CoreDao(DaoConfig.forDatabase(self.__dbName))
queryResults = dao.executeMappedSQLQuery(self.__query)
response = ArrayList()
response.add(ResponseMessageGeneric(queryResults))
return response

View file

@ -1,46 +0,0 @@
##
# 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.
##
from com.raytheon.uf.edex.database.tasks import SqlStatementTask
from com.raytheon.uf.common.message.response import ResponseMessageGeneric
from java.util import ArrayList
#
# Generalized query script for executing non query type sql statements
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 10/21/08 #1615 bphillip Initial Creation.
#
#
class SqlStatement():
def __init__(self, sqlQuery,dbName="metadata"):
self.__stmt = SqlStatementTask(sqlQuery,dbName)
def execute(self):
result = self.__stmt.execute()
response = ArrayList()
response.add(ResponseMessageGeneric(result))
return response

View file

@ -93,8 +93,9 @@ import com.vividsolutions.jts.io.WKTWriter;
* Apr 21, 2014 2060 njensen Remove dependency on grid dataURI column
* Apr 22, 2014 2984 njensen Remove dependency on edex/CoreDao
* Nov 18, 2014 3831 dhladky StatusHandler logging. Proper list sizing.
*
* Jul 13, 2015 4500 rjpeter Fix SQL Injection concerns.
* </pre>
*
* @author dhladky
* @version 1
*/
@ -117,7 +118,7 @@ public class FFMPUtils {
public static float MISSING = -99999.0f;
private static NumberFormat formatter = new DecimalFormat("#.##");
private static final IUFStatusHandler statusHandler = UFStatus
.getHandler(FFMPUtils.class);
@ -178,26 +179,26 @@ public class FFMPUtils {
if (results.length > 0) {
if (mode.equals("CAVE")) {
for (int i = 0; i < results.length; i++) {
Object[] results2 = (Object[]) results[i];
for (int j = 0; j < results2.length; j++) {
if (((String) results2[j]) != null) {
pfafs.add(Long.parseLong((String) results2[j]));
for (Object result : results) {
Object[] results2 = (Object[]) result;
for (Object element : results2) {
if (((String) element) != null) {
pfafs.add(Long.parseLong((String) element));
}
}
}
}
else {
for (int j = 0; j < results.length; j++) {
if (((String) results[j]) != null) {
pfafs.add(Long.parseLong((String) results[j]));
for (Object result : results) {
if (((String) result) != null) {
pfafs.add(Long.parseLong((String) result));
}
}
}
}
} catch (SpatialException e) {
statusHandler.error("Error querying allPfafs: +sql: "+sql, e);
statusHandler.error("Error querying allPfafs: +sql: " + sql, e);
}
return pfafs;
@ -217,12 +218,12 @@ public class FFMPUtils {
* DR 13228 state added to the below query
*/
String sql = "SELECT lid, county, name, lat, lon, state FROM location "
+ "where lid in " + "(select distinct(lid) from IngestFilter "
+ "where pe in ('PC', 'PP') " + "and ingest = 'T' "
+ "and dur < 2000)";
+ "where lid in (select distinct(lid) from IngestFilter "
+ "where pe in ('PC', 'PP') and ingest = 'T' and dur < 2000)";
try {
Object[] results = executeSqlQuery(sql, ShefConstants.IHFS);
virtualBasins = new LinkedHashMap<String, FFMPVirtualGageBasinMetaData>(results.length, 1.0f);
virtualBasins = new LinkedHashMap<String, FFMPVirtualGageBasinMetaData>(
results.length, 1.0f);
Geometry poly = getCwaGeometry(cwa, mode);
PreparedGeometry pg = PreparedGeometryFactory.prepare(poly);
Coordinate coor = poly.getCentroid().getCoordinate();
@ -242,7 +243,8 @@ public class FFMPUtils {
}
}
} catch (Exception e) {
statusHandler.error("Error querying Virtual Gage's: +sql: "+sql, e);
statusHandler.error("Error querying Virtual Gage's: +sql: " + sql,
e);
}
return virtualBasins;
@ -266,8 +268,8 @@ public class FFMPUtils {
int j = 1;
if (results.length > 0) {
for (int i = 0; i < results.length; i++) {
String column_name = (String) results[i]/*((Object[]) results[i])[0]*/;
for (Object result : results) {
String column_name = (String) result;
if (column_name.startsWith("upstream")) {
upstreams.add("upstream" + j);
j++;
@ -275,7 +277,8 @@ public class FFMPUtils {
}
}
} catch (SpatialException e) {
statusHandler.error("Error determining upstream depth: +sql: "+sql, e);
statusHandler.error("Error determining upstream depth: +sql: "
+ sql, e);
}
return upstreams;
@ -304,7 +307,8 @@ public class FFMPUtils {
sq = SpatialQueryFactory.create();
results = sq.dbRequest(sql.toString(), MAPS_DB);
} catch (SpatialException e) {
statusHandler.error("Failed to lookup Huc Parameters: sql: "+sql, e);
statusHandler.error("Failed to lookup Huc Parameters: sql: " + sql,
e);
}
String[] pfafs = new String[results.length];
@ -321,8 +325,8 @@ public class FFMPUtils {
int maxDepth = prelimstartDepth;
int startDepth = prelimstartDepth;
for (int i = 0; i < pfafs.length; i++) {
int depth = pfafs[i].substring(prelimstartDepth).indexOf("0");
for (String pfaf : pfafs) {
int depth = pfaf.substring(prelimstartDepth).indexOf("0");
depth = prelimstartDepth + depth;
if (depth > maxDepth) {
maxDepth = depth;
@ -333,15 +337,14 @@ public class FFMPUtils {
if (pfafs.length > 0) {
for (int myMinDepth = maxDepth; myMinDepth > 0; myMinDepth--) {
int ilevelcount = 0;
for (int i = 0; i < pfafs.length; i++) {
int idepth = pfafs[i].substring(prelimstartDepth).indexOf(
"0");
for (String pfaf : pfafs) {
int idepth = pfaf.substring(prelimstartDepth).indexOf("0");
idepth = prelimstartDepth + idepth;
if (idepth >= myMinDepth) {
ilevelcount++;
}
}
if ((ilevelcount / pfafs.length) * 100 < 80) {
if (((ilevelcount / pfafs.length) * 100) < 80) {
startDepth = myMinDepth;
} else {
break;
@ -397,7 +400,8 @@ public class FFMPUtils {
sq = SpatialQueryFactory.create();
results = sq.dbRequest(sql.toString(), MAPS_DB);
} catch (SpatialException e) {
statusHandler.error("Error getting basins: sql:"+sql+"\n", e);
statusHandler.error("Error getting basins: sql:" + sql + "\n",
e);
}
return results;
@ -440,7 +444,8 @@ public class FFMPUtils {
results = sq.dbRequest(builder.toString(), MAPS_DB);
rval = new HashMap<Long, Geometry>(results.length, 1.0f);
} catch (SpatialException e) {
statusHandler.error("Error querying Raw Geometries: +sql: "+builder.toString(), e);
statusHandler.error("Error querying Raw Geometries: +sql: "
+ builder.toString(), e);
}
WKBReader wkbReader = new WKBReader();
@ -516,8 +521,8 @@ public class FFMPUtils {
// sql, FFMPUtils.MAPS_DB, QueryLanguage.SQL);
if (results.length > 0) {
if (mode.equals("EDEX")) {
for (int i = 0; i < results.length; i++) {
Object[] results2 = (Object[]) results[i];
for (Object result : results) {
Object[] results2 = (Object[]) result;
String countyName = null;
String state = null;
@ -537,14 +542,14 @@ public class FFMPUtils {
}
} else {
for (int i = 0; i < results.length; i++) {
for (Object result : results) {
String countyName = null;
String state = null;
Object[] results2 = null;
try {
results2 = (Object[]) results[i];
results2 = (Object[]) result;
if (results2[0] instanceof String) {
countyName = (String) results2[0];
@ -576,7 +581,7 @@ public class FFMPUtils {
}
}
} catch (SpatialException e) {
statusHandler.error("Error retrieving COUNTY, pfaf: "+pfaf, e);
statusHandler.error("Error retrieving COUNTY, pfaf: " + pfaf, e);
}
return county;
@ -612,17 +617,16 @@ public class FFMPUtils {
if (results != null) {
if (results.length > 0) {
for (int i = 0; i < results.length; i++) {
if (results[i] != null) {
keys.add(new Integer(
(String)results[i]/* ((Object[]) results[i])[0]*/)
.longValue());
for (Object result : results) {
if (result != null) {
keys.add(new Integer((String) result).longValue());
}
}
}
}
} catch (SpatialException e) {
statusHandler.error("Error retreiving COUNTY FIPS list! sql: "+sql, e);
statusHandler.error("Error retreiving COUNTY FIPS list! sql: "
+ sql, e);
}
return removeDuplicates(keys);
@ -681,16 +685,17 @@ public class FFMPUtils {
if (results != null) {
gids = new ArrayList<Long>(results.length);
if (results.length > 0) {
for (int i = 0; i < results.length; i++) {
gids.add(((Number) results[i]).longValue());
for (Object result : results) {
gids.add(((Number) result).longValue());
}
}
}
} catch (SpatialException e) {
statusHandler.error("Error retreiving COUNTY INFO, part 1! sql: "+sql1, e);
statusHandler.error("Error retreiving COUNTY INFO, part 1! sql: "
+ sql1, e);
}
Geometry geom = null;
String countyName = null;
String state = null;
@ -711,10 +716,10 @@ public class FFMPUtils {
Object[] results = sq.dbRequest(sql, FFMPUtils.MAPS_DB);
if (results.length > 0) {
for (int i = 0; i < results.length; i++) {
Object[] results2 = (Object[]) results[i];
for (Object result : results) {
Object[] results2 = (Object[]) result;
WKBReader wkbReader = new WKBReader();
if (results2[0] != null) {
if (geom == null) {
geom = readGeometry(results2[0], wkbReader);
@ -736,7 +741,8 @@ public class FFMPUtils {
}
} catch (SpatialException e) {
statusHandler.error("Error retreiving COUNTY INFO, part 2! sql: "+sql, e);
statusHandler.error(
"Error retreiving COUNTY INFO, part 2! sql: " + sql, e);
} catch (ParseException e) {
statusHandler.error("Error parsing COUNTY INFO!", e);
}
@ -777,7 +783,8 @@ public class FFMPUtils {
}
} catch (SpatialException e) {
statusHandler.error("Error retrieving basins: sql: "+sql+"\n basin: "+basinId);
statusHandler.error("Error retrieving basins: sql: " + sql
+ "\n basin: " + basinId);
}
return pfaf;
@ -811,7 +818,8 @@ public class FFMPUtils {
coor = new Coordinate(lon, lat);
} catch (SpatialException e) {
statusHandler.error("Error getting radar geometry description: "+sql, e);
statusHandler.error("Error getting radar geometry description: "
+ sql, e);
}
return coor;
@ -842,7 +850,7 @@ public class FFMPUtils {
statusHandler.error("Error parsing CWA geometry!", e);
}
} catch (SpatialException e) {
statusHandler.error("Error querying CWA geometry: "+sql, e);
statusHandler.error("Error querying CWA geometry: " + sql, e);
}
return geo;
@ -869,12 +877,12 @@ public class FFMPUtils {
cwas = new ArrayList<String>();
if (results.length > 0) {
for (int i = 0; i < results.length; i++) {
cwas.add((String) results[i]);
for (Object result : results) {
cwas.add((String) result);
}
}
} catch (Exception e) {
statusHandler.error("Error querying CWA descriptions!: "+sql, e);
statusHandler.error("Error querying CWA descriptions!: " + sql, e);
}
return cwas;
@ -909,7 +917,7 @@ public class FFMPUtils {
rfc = SiteMap.getInstance().getSite4LetterId(rfc.toUpperCase());
}
} catch (Exception e) {
statusHandler.error("Error querying RFC designation: "+sql, e);
statusHandler.error("Error querying RFC designation: " + sql, e);
}
return rfc;
@ -937,14 +945,15 @@ public class FFMPUtils {
DbQueryResponse response = (DbQueryResponse) RequestRouter
.route(request);
ffgHash = new HashSet<String>(response.getResults().size(), 1.0f);
for (Map<String, Object> map : response.getResults()) {
String key = (String) map
.get(GridConstants.PARAMETER_ABBREVIATION);
ffgHash.add(key);
}
} catch (Exception e) {
statusHandler.error("Error querying FFG parameters: "+request.toString(), e);
statusHandler.error(
"Error querying FFG parameters: " + request.toString(), e);
}
return ffgHash;
@ -970,7 +979,8 @@ public class FFMPUtils {
.route(request);
return response.getEntityObjects(GridRecord.class)[0].getDataURI();
} catch (Exception e) {
statusHandler.error("Error querying FFG Data URIS: "+request.toString(), e);
statusHandler.error(
"Error querying FFG Data URIS: " + request.toString(), e);
}
return null;
@ -995,7 +1005,7 @@ public class FFMPUtils {
uri = (String) results[0];
}
} catch (SpatialException e) {
statusHandler.error("Error querying RADAR Data URI: "+sql, e);
statusHandler.error("Error querying RADAR Data URI: " + sql, e);
}
return uri;
@ -1023,7 +1033,8 @@ public class FFMPUtils {
subGrid = new HRAPSubGrid(extent, gridFactor);
} catch (Exception e) {
statusHandler.error("Error looking up XMRG geometry: "+xmrg.toString(), e);
statusHandler.error(
"Error looking up XMRG geometry: " + xmrg.toString(), e);
}
return MapUtil.getGridGeometry(subGrid);
@ -1051,7 +1062,8 @@ public class FFMPUtils {
subGrid = new HRAPSubGrid(extent, gridFactor);
} catch (Exception e) {
statusHandler.error("Error querying XMRG sub grid: "+xmrg.toString(), e);
statusHandler.error(
"Error querying XMRG sub grid: " + xmrg.toString(), e);
}
return subGrid;
@ -1388,14 +1400,8 @@ public class FFMPUtils {
*/
private static Object[] executeSqlQuery(String query, String database)
throws Exception {
// code shamelessly modeled after DirectDbQuery
// TODO DirectDbQuery should be changed to use RequestRouter instead of
// ThriftClient and should be promoted to a common plugin
Map<String, RequestConstraint> constraints = new HashMap<String, RequestConstraint>();
constraints.put("query", new RequestConstraint(query));
constraints.put("database", new RequestConstraint(database));
constraints.put("mode", new RequestConstraint("sqlquery"));
QlServerRequest request = new QlServerRequest(constraints);
QlServerRequest request = new QlServerRequest(query);
request.setDatabase(database);
ResponseMessageGeneric resp = (ResponseMessageGeneric) RequestRouter
.route(request);

View file

@ -55,6 +55,7 @@ import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.uf.common.time.TimeRange;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.vividsolutions.jts.geom.Geometry;
/**
@ -78,6 +79,7 @@ import com.vividsolutions.jts.geom.Geometry;
* Jul 30, 2014 3184 njensen Overrode required and optional identifiers
* Feb 27, 2015 4180 mapeters Overrode getAvailableParameters().
* Jun 15, 2015 4560 ccody Added support for configurable rate/accumulation calculation for getGeometryData
* Jul 16, 2015 4658 dhladky Expiration times fixed.
*
* </pre>
*
@ -252,9 +254,6 @@ public class FFMPGeometryFactory extends AbstractDataPluginFactory {
HucLevelGeometriesFactory geomFactory = HucLevelGeometriesFactory
.getInstance();
// BAL - Switched to use siteKey instead of dataKey.
// Map<Long, Geometry> geomMap = geomFactory.getGeometries(templates,
// dataKey, cwa, huc);
Map<Long, Geometry> geomMap = geomFactory.getGeometries(templates,
siteKey, cwa, huc);
@ -303,18 +302,14 @@ public class FFMPGeometryFactory extends AbstractDataPluginFactory {
}
if (basin instanceof FFMPGuidanceBasin) {
/*
* Bryon L - Added test for FFMPGuidanceBasin object.
* Couldn't use getValue(Date, Sourcename) here. Odd problem
* with date key reference.
*/
value = ((FFMPGuidanceBasin) basin).getValue(
rec.getSourceName(), 1000);
rec.getSourceName(),
sourceXml.getExpirationMinutes(rec.getSiteKey())
* TimeUtil.MILLIS_PER_MINUTE);
} else {
value = basin.getAccumValue(start, end,
sourceXml.getExpirationMinutes(rec.getSiteKey()),
isRate);
// value = basin.getValue(rec.getDataTime().getRefTime());
sourceXml.getExpirationMinutes(rec.getSiteKey())
* TimeUtil.MILLIS_PER_MINUTE, isRate);
}
String parameter = rec.getSourceName();
String unitStr = sourceXml.getUnit();

View file

@ -980,17 +980,13 @@ public class GridLocation extends PersistableDataObject<String> implements
PixelOrientation.CENTER, this);
mt.transform(gridCells, 0, latLon, 0, gridCells.length / 2);
} catch (Exception e) {
e.printStackTrace();
statusHandler.error("Error computing lat/lon grid", e);
}
/*
* FIXME We reverse the x and y dimensions because that's what AWIPS 1
* did and that makes the pre-existing python code compatible. Java
* ordering is x,y while python is ordering is y,x. It's confusing and
* questionable at best so someday someone should correct all that. Good
* luck.
* return the 1-d array and let python reshape it
*/
return new NDArray<float[]>(latLon, ny, nx, 2);
return new NDArray<float[]>(latLon, 1, latLon.length);
}
/**

View file

@ -20,7 +20,7 @@
-->
<DerivedParameter abbreviation="MnT12hr" name="12-hr Minimum Temperature" unit="K">
<Method name="Alias" levels="Surface"
models="MOSGuide" displayName="Minimum Temperature">
models="MOSGuide NationalBlend" displayName="Minimum Temperature">
<Field abbreviation="MnT12hr" level="2FHAG"/>
</Method>
</DerivedParameter>

View file

@ -20,7 +20,7 @@
-->
<DerivedParameter abbreviation="MxT12hr" name="12-hr Maximum Temperature" unit="K">
<Method name="Alias" levels="Surface"
models="MOSGuide" displayName="Maximum Temperature">
models="MOSGuide NationalBlend" displayName="Maximum Temperature">
<Field abbreviation="MxT12hr" level="2FHAG"/>
</Method>
</DerivedParameter>

View file

@ -147,9 +147,9 @@ FOR <L>${hycType}</L> ##
#if(${alaska}=="true")
${expcanHLTag} !**INSERT RIVER/STREAM OR AREA**! IN !**INSERT GEO AREA**!...
#elseif(${wrZoneCounty}=="true")
${expcanHLTag} #headlineLocList(${affectedCounties} true true true false)...
${expcanHLTag} #headlineLocList(${affectedCounties} true true true false, "ALL")...
#else
${expcanHLTag} #headlineLocList(${areas} true true true false)...
${expcanHLTag} #headlineLocList(${areas} true true true false, "ALL")...
#end
### GP end
@ -162,9 +162,9 @@ FOR <L>${hycType}</L> ##
#if(${alaska}=="true")
${expcanHLTag} !**INSERT RIVER/STREAM OR AREA**! IN !**INSERT GEO AREA**!...
#elseif(${wrZoneCounty}=="true")
${expcanHLTag} #headlineLocList(${cancelaffectedCounties} true true true false)...
${expcanHLTag} #headlineLocList(${cancelaffectedCounties} true true true false, "ALL")...
#else
${expcanHLTag} #headlineLocList(${cancelareas} true true true false)...
${expcanHLTag} #headlineLocList(${cancelareas} true true true false, "ALL")...
#end
### GP end
#end
@ -249,14 +249,14 @@ THIS IS A TEST MESSAGE.##
#if(${hycType} != "")
FOR <L>${hycType}</L> ##
#end
REMAINS IN EFFECT #secondBullet(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) FOR ##
REMAINS IN EFFECT UNTIL #headlineExpire(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) FOR ##
### added by GP
#if(${alaska}=="true")
!**INSERT RIVER/STREAM OR AREA**! IN !**INSERT GEO AREA**!...
#elseif(${wrZoneCounty}=="true")
#headlineLocList(${affectedCounties} true true true false)...
#headlineLocList(${affectedCounties} true true true false, "ALL")...
#else
#headlineLocList(${areas} true true true false)...
#headlineLocList(${areas} true true true false, "ALL")...
#end
### GP end

View file

@ -219,7 +219,7 @@ THIS IS A TEST MESSAGE.##
#if(${hycType} != "")
FOR <L>${hycType}</L> ##
#end
REMAINS IN EFFECT #headlineExpire(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) FOR ##
REMAINS IN EFFECT UNTIL #headlineExpire(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) FOR ##
#headlineLocList(${areas} true true true false "ALL")...
################################################

View file

@ -30,7 +30,7 @@ ${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#if(${productClass}=="T")
This message is for test purposes only
...THIS MESSAGE IS FOR TEST PURPOSES ONLY...
#end
#headline(${officeLoc}, ${backupSite})
@ -40,7 +40,7 @@ This message is for test purposes only
##################
* ##
#if(${productClass}=="T")
This is a test message. ##
THIS IS A TEST MESSAGE. ##
#end
Extreme Wind Warning for...
#firstBullet(${areas})
@ -50,7 +50,7 @@ Extreme Wind Warning for...
###################
* ##
#if(${productClass}=="T")
This is a test message. ##
THIS IS A TEST MESSAGE. ##
#end
#secondBullet(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone})
@ -113,7 +113,7 @@ This is a test message. ##
* ##
#if(${productClass}=="T")
This is a test message. ##
THIS IS A TEST MESSAGE. ##
#end
#thirdBullet(${dateUtil},${event},${timeFormat},${localtimezone},${secondtimezone})
, ${reportType}, ${reportType1} ##
@ -135,14 +135,14 @@ This is a test message. ##
#if(${list.contains(${bullets}, "pathcast")})
* ##
#if(${productClass}=="T")
This is a test message. ##
THIS IS A TEST MESSAGE. ##
#end
#pathCast("${phenomena} will be near..." ${phenomena} ${pathCast} ${otherPoints} ${areas} ${dateUtil} ${timeFormat} 0)
#elseif(${list.contains(${bullets}, "listofcities")})
* ##
#if(${productClass}=="T")
This is a test message. ##
THIS IS A TEST MESSAGE. ##
#end
#### THE THIRD ARGUMENT IS A NUMBER SPECIFYING THE NUMBER OF COLUMNS TO OUTPUT THE CITIES LIST IN
#### 0 IS A , SEPARATED LIST, 1 IS ONE PER LINE, >1 IS A COLUMN FORMAT
@ -167,11 +167,11 @@ This is a test message. ##
#end
##
#if(${ctaSelected} == "YES")
PRECAUTIONARY/PREPAREDNESS ACTIONS,
PRECAUTIONARY/PREPAREDNESS ACTIONS...
#end
#if(${list.contains(${bullets}, "destructiveWindsCTA")})
Widespread destructive winds of !** **! TO !** **! mph will spread across ##
Widespread destructive winds of !** **! to !** **! mph will spread across ##
#foreach (${area} in ${areas})
${area.name} ${area.areaNotation}, ##
#end
@ -202,7 +202,7 @@ The safest place to be during a major landfalling hurricane is in a reinforced i
#if(${productClass}=="T")
This is a test message. do not take action based on this message.
THIS IS A TEST MESSAGE. DO NOT TAKE ACTION BASED ON THIS MESSAGE.
#end
#printcoords(${areaPoly}, ${list})

View file

@ -40,13 +40,13 @@ ${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#if(${productClass}=="T")
THIS MESSAGE IS FOR TEST PURPOSES ONLY.
...THIS MESSAGE IS FOR TEST PURPOSES ONLY...
#end
${ugcline}
/${productClass}.${action}.${vtecOffice}.${phenomena}.W.${etn}.000000T0000Z-${dateUtil.format(${expire}, ${timeFormat.ymdthmz})}/
#foreach (${area} in ${areas})
#captialize(${area.name} "ALL")
#capitalize(${area.name} "ALL")
#if(${includeStateAbbreviation}==true)
${area.stateabbr}##
#end
@ -57,14 +57,14 @@ ${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#if(${productClass}=="T")
THIS MESSAGE IS FOR TEST PURPOSES ONLY.
...THIS MESSAGE IS FOR TEST PURPOSES ONLY...
#end
#if(${productClass}=="T")
THIS IS A TEST MESSAGE. ##
#end
THE EXTREME WIND WARNING FOR ##
#headlineLocList(${areas} true true true false "ALL") ${expcanHLTag},
...THE EXTREME WIND WARNING FOR ##
#headlineLocList(${areas} true true true false "ALL") ${expcanHLTag}...
## One line explanation
!**EXPLANATION**!
@ -146,15 +146,14 @@ National Weather Service ${officeShort}
#backupText(${backupSite})
${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#if(${productClass}=="T")
THIS MESSAGE IS FOR TEST PURPOSES ONLY.
...THIS MESSAGE IS FOR TEST PURPOSES ONLY...
#end
${ugcline}
/${productClass}.${action}.${vtecOffice}.${phenomena}.W.${etn}.000000T0000Z-${dateUtil.format(${expire}, ${timeFormat.ymdthmz})}/
#foreach (${area} in ${areas})
#captialize(${area.name} "ALL")
#capitalize(${area.name} "ALL")
#if(${includeStateAbbreviation}==true)
${area.stateabbr}##
#end
@ -163,16 +162,15 @@ ${ugcline}
${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#if(${productClass}=="T")
THIS MESSAGE IS FOR TEST PURPOSES ONLY.
...THIS MESSAGE IS FOR TEST PURPOSES ONLY...
#end
#if(${productClass}=="T")
THIS IS A TEST MESSAGE. ##
#end
An extreme wind warning remains in effect until #headlineExpire(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) for ##
#headlineLocList(${areas} true true true false "ALL"),
...AN EXTREME WIND WARNING REMAINS IN EFFECT UNTIL #headlineExpire(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) FOR ##
#headlineLocList(${areas} true true true false "ALL")...
## Storm current location description
#if(${productClass}=="T")
@ -224,11 +222,11 @@ THIS IS A TEST MESSAGE. ##
## CALL TO ACTIONS ##
#####################
#if(${list.contains(${bullets}, "cta1")} || ${list.contains(${bullets}, "cta2")} || ${list.contains(${bullets}, "cta3")})
PRECAUTIONARY/PREPAREDNESS ACTIONS...
PRECAUTIONARY/PREPAREDNESS ACTIONS...
#end
#if(${list.contains(${bullets}, "cta1")})
Widespread destructive winds of !** **! TO !** **! mph will spread across ##
Widespread destructive winds of !** **! to !** **! mph will spread across ##
#headlineLocList(${areas} true true true false), Producing swaths of tornado-like damage.
#end
@ -319,13 +317,13 @@ ${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#if(${productClass}=="T")
THIS MESSAGE IS FOR TEST PURPOSES ONLY.
...THIS MESSAGE IS FOR TEST PURPOSES ONLY...
#end
${ugclinecan}
/${productClass}.CAN.${vtecOffice}.${phenomena}.W.${etn}.000000T0000Z-${dateUtil.format(${expire}, ${timeFormat.ymdthmz})}/
#foreach (${area} in ${cancelareas})
#captialize(${area.name} "ALL")
#capitalize(${area.name} "ALL")
#if(${includeStateAbbreviation}==true)
${area.stateabbr}##
#end
@ -336,16 +334,16 @@ ${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#if(${productClass}=="T")
THIS MESSAGE IS FOR TEST PURPOSES ONLY.
...THIS MESSAGE IS FOR TEST PURPOSES ONLY...
#end
#if(${productClass}=="T")
THIS IS A TEST MESSAGE.##
#end
THE EXTREME WIND WARNING FOR ##
#headlineLocList(${cancelareas} true true true false "ALL") ${expcanHLTag},
...THE EXTREME WIND WARNING FOR ##
#headlineLocList(${cancelareas} true true true false "ALL") ${expcanHLTag}...
###REPLACE headlineLocList ABOVE WITH THE FOLLOWING FOR ZONE BASED PRODUCT W/ COUNTY HEADLINE
###headlineLocList(${cancelaffectedCounties} true true true false "ALL") ${expcanHLTag},
###headlineLocList(${cancelaffectedCounties} true true true false "ALL") ${expcanHLTag}...
## One line explanation
!**EXPLANATION**!
@ -373,7 +371,7 @@ $$
${ugcline}
/${productClass}.CON.${vtecOffice}.${phenomena}.W.${etn}.000000T0000Z-${dateUtil.format(${expire}, ${timeFormat.ymdthmz})}/
#foreach (${area} in ${areas})
#captialize(${area.name} "ALL")
#capitalize(${area.name} "ALL")
#if(${includeStateAbbreviation}==true)
${area.stateabbr}##
#end
@ -384,21 +382,21 @@ ${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#if(${productClass}=="T")
THIS MESSAGE IS FOR TEST PURPOSES ONLY.
...THIS MESSAGE IS FOR TEST PURPOSES ONLY...
#end
#if(${productClass}=="T")
THIS IS A TEST MESSAGE.##
#end
An extreme wind warning remains in effect until #headlineExpire(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) for ##
#headlineLocList(${areas} true true true false "ALL"),
...AN EXTREME WIND WARNING REMAINS IN EFFECT UNTIL #headlineExpire(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) FOR ##
#headlineLocList(${areas} true true true false "ALL")...
#if(${productClass}=="T")
THIS IS A TEST MESSAGE. AT ${dateUtil.format(${event}, ${timeFormat.clock}, ${localtimezone})}, ${reportType}, ${reportType1} ##
THIS IS A TEST MESSAGE. At ${dateUtil.format(${event}, ${timeFormat.clock}, ${localtimezone})}, ${reportType}, ${reportType1} ##
#else
at ${dateUtil.format(${event}, ${timeFormat.clock}, ${localtimezone})}, ${reportType}, ${reportType1} ##
At ${dateUtil.format(${event}, ${timeFormat.clock}, ${localtimezone})}, ${reportType}, ${reportType1} ##
#end
##Many of the variables passed below are controlled by config.vm
#if(${stormType} == "line")
@ -447,12 +445,12 @@ THIS IS A TEST MESSAGE. ##
#end
##
#if(${ctaSelected} == "YES")
PRECUATIONARY/PREPAREDNESS ACTIONS...
PRECAUTIONARY/PREPAREDNESS ACTIONS...
#end
##
#if(${list.contains(${bullets}, "destructiveWindsCTA")})
Widespread destructive winds of !** **! TO !** **! mph will spread across ##
Widespread destructive winds of !** **! to !** **! mph will spread across ##
#foreach (${area} in ${areas})
${area.name} ${area.areaNotation}, ##
#end
@ -499,7 +497,7 @@ ${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
${ugcline}
/${productClass}.${action}.${vtecOffice}.${phenomena}.W.${etn}.000000T0000Z-${dateUtil.format(${expire}, ${timeFormat.ymdthmz})}/
#foreach (${area} in ${areas})
#captialize(${area.name} "ALL")
#capitalize(${area.name} "ALL")
#if(${includeStateAbbreviation}==true)
${area.stateabbr}##
#end
@ -510,14 +508,14 @@ ${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#if(${productClass}=="T")
THIS MESSAGE IS FOR TEST PURPOSES ONLY.
...THIS MESSAGE IS FOR TEST PURPOSES ONLY...
#end
#if(${productClass}=="T")
THIS IS A TEST MESSAGE.##
#end
THE EXTREME WIND WARNING FOR##
#headlineLocList(${areas} true true true false "ALL") ${expcanHLTag},
...THE EXTREME WIND WARNING FOR ##
#headlineLocList(${areas} true true true false "ALL") ${expcanHLTag}...
#############
## WATCHES ##
@ -529,7 +527,7 @@ THE EXTREME WIND WARNING FOR##
#insertsvrwatches(${watches}, ${list}, ${secondtimezone}, ${dateUtil}, ${timeFormat})
#end
#end
&&
#if(${productClass}=="T")
THIS IS A TEST MESSAGE. DO NOT TAKE ACTION BASED ON THIS MESSAGE.

View file

@ -1,10 +1,10 @@
ER \ RAIN
SM \ SNOW MELT
SM \ SNOWMELT
SM \ MELTING SNOW
SM \ VOLCANIC SNOW MELT
SM \ VOLCANIC SNOWMELT
IJ \ ICE JAM
IC \ ICE JAM AND RAIN
IC \ ICE JAM AND SNOW MELT
IC \ ICE JAM AND SNOWMELT
GO \ GLACIER
GO \ GLACIER-DAMMED LAKE
DM \ DAM
@ -13,4 +13,4 @@ DR \ DAM FLOODGATE
DM \ LEVEE FAILURE
DM \ DAM FAILURE
DM \ DAM BREAK
RS \ RAIN AND SNOW MELT
RS \ RAIN AND SNOWMELT

View file

@ -395,7 +395,7 @@ ${dateUtil.format(${now}, ${timeFormat.header}, ${localtimezone})}
#end
#if(${action}=="CANCON" || ${action}=="CON" || ${action}=="COR" || ${CORCAN}=="true")
...A ${eventType} WARNING REMAINS IN EFFECT #headlineExpire(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) for ##
...A ${eventType} WARNING REMAINS IN EFFECT UNTIL #headlineExpire(${dateUtil},${expire},${timeFormat},${localtimezone},${secondtimezone}) for ##
#headlineLocList(${areas} true true true false "ALL")...
########### END NEW HEADLINE CODE ####################
#set($reportType = "!** BASIS FOR WARNING **!")

View file

@ -117,7 +117,7 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery;
* Apr 28, 2015 #4027 randerso Expunged Calendar from ActiveTableRecord,
* fixed next ETN query to query for >= Jan 1
* May 22, 2015 4522 randerso Create proper primary key for ActiveTableRecord
*
* Jul 09, 2015 4500 rjpeter Fix SQL Injection concern.
* </pre>
*
* @author njensen
@ -743,12 +743,11 @@ public class ActiveTable {
throws DataAccessLayerException {
CoreDao dao = practiceDao;
String sql = "delete from practice_activetable;";
dao.executeNativeSql(sql);
dao.executeSQLUpdate(sql);
sql = "delete from cluster_task where name ='"
+ GetNextEtnUtil.getEtnClusterLockName(requestedSiteId,
ActiveTableMode.PRACTICE) + "';";
dao.executeNativeSql(sql);
sql = "delete from cluster_task where name = :name";
dao.executeSQLUpdate(sql, "name", GetNextEtnUtil.getEtnClusterLockName(
requestedSiteId, ActiveTableMode.PRACTICE));
}
/**

View file

@ -28,8 +28,6 @@ import java.io.FileWriter;
import java.io.IOException;
import com.raytheon.uf.common.awipstools.GetWfoCenterPoint;
import com.raytheon.uf.common.dataquery.db.QueryResult;
import com.raytheon.uf.common.dataquery.db.QueryResultRow;
import com.raytheon.uf.common.localization.IPathManager;
import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType;
@ -38,7 +36,6 @@ import com.raytheon.uf.common.serialization.comm.IRequestHandler;
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.edex.database.DataAccessLayerException;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
import com.vividsolutions.jts.geom.Coordinate;
@ -52,8 +49,8 @@ import com.vividsolutions.jts.geom.Coordinate;
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jun 9, 2010 mschenke Initial creation
*
* Jun 9, 2010 mschenke Initial creation
* Jul 09, 2015 4500 rjpeter Fix SQL Injection concern.
* </pre>
*
* @author mschenke
@ -98,25 +95,22 @@ public class GetWfoCenterHandler implements IRequestHandler<GetWfoCenterPoint> {
private static Coordinate lookupInWfoCenter(String wfoId) {
Coordinate loc = null;
try {
String query = String.format(
"SELECT lat,lon FROM mapdata.cwa WHERE wfo = '%s' LIMIT 1",
wfoId);
QueryResult result = (QueryResult) new CoreDao(
DaoConfig.forDatabase("maps")).executeNativeSql(query);
CoreDao dao = new CoreDao(DaoConfig.forDatabase("maps"));
Object[] rows = dao.executeSQLQuery(
"SELECT lat,lon FROM mapdata.cwa WHERE wfo = :wfo LIMIT 1",
"wfo", wfoId);
if (result.getRows().length == 0) {
query = String
.format("select ST_Y(theCentroid) as lat, ST_X(theCentroid) as lon from (select ST_CENTROID(theUnion) as theCentroid from (select ST_Union(the_geom) as theUnion from mapdata.rfc where site_id = '%s') as dummyAlias) as dummyAlias;",
wfoId);
result = (QueryResult) new CoreDao(
DaoConfig.forDatabase("maps")).executeNativeSql(query);
if ((rows == null) || (rows.length == 0)) {
rows = dao
.executeSQLQuery(
"select ST_Y(theCentroid) as lat, ST_X(theCentroid) as lon from (select ST_CENTROID(theUnion) as theCentroid from (select ST_Union(the_geom) as theUnion from mapdata.rfc where site_id = :site) as dummyAlias) as dummyAlias",
"site", wfoId);
}
if (result.getRows().length > 0) {
QueryResultRow row = result.getRows()[0];
Double lat = ((Number) row.getColumn(0)).doubleValue();
Double lon = ((Number) row.getColumn(1)).doubleValue();
if ((rows != null) && (rows.length > 0)) {
Object[] row = (Object[]) rows[0];
Double lat = ((Number) row[0]).doubleValue();
Double lon = ((Number) row[1]).doubleValue();
loc = new Coordinate(lon, lat);
}
@ -124,7 +118,7 @@ public class GetWfoCenterHandler implements IRequestHandler<GetWfoCenterPoint> {
statusHandler.handle(Priority.PROBLEM,
"No location information found for wfo: " + wfoId);
}
} catch (DataAccessLayerException e) {
} catch (Exception e) {
statusHandler.handle(Priority.PROBLEM,
"Error executing query for wfo center point", e);
}
@ -152,7 +146,8 @@ public class GetWfoCenterHandler implements IRequestHandler<GetWfoCenterPoint> {
double lat = Double.parseDouble(line.substring(0, p));
double lon = Double.parseDouble(line.substring(p));
if (lat > 90.0 || lat < -90.0 || lon > 180.0 || lon < -180.0) {
if ((lat > 90.0) || (lat < -90.0) || (lon > 180.0)
|| (lon < -180.0)) {
statusHandler
.handle(Priority.PROBLEM,
"Invalid lat/lon in wfo center point file, using default");

View file

@ -21,13 +21,18 @@ package com.raytheon.uf.edex.metartohmdb.dao;
import java.util.Calendar;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
import com.raytheon.uf.edex.decodertools.time.TimeTools;
/**
* TODO Add Description
* Dao for HMDBReport.
*
* <pre>
*
@ -37,7 +42,7 @@ import com.raytheon.uf.edex.decodertools.time.TimeTools;
* ------------ ---------- ----------- --------------------------
* Jun 29, 2009 jkorman Initial creation
* Sep 18, 2014 #3627 mapeters Updated deprecated {@link TimeTools} usage.
*
* Jun 18, 2015 4500 rjpeter Fix SQL Injection concern.
* </pre>
*
* @author jkorman
@ -46,7 +51,7 @@ import com.raytheon.uf.edex.decodertools.time.TimeTools;
public class HMDBRptDao extends CoreDao {
private static final Object LOCK = new Object();
public HMDBRptDao() {
super(DaoConfig.forClass("hmdb", HMDBReport.class));
}
@ -58,43 +63,46 @@ public class HMDBRptDao extends CoreDao {
*/
public boolean storeToTable(HMDBReport report) {
boolean status = true;
synchronized(LOCK) {
synchronized (LOCK) {
logger.debug("SQL = " + report.toInsertSQL());
try {
status = (executeSQLUpdate(report.toInsertSQL()) == 1);
} catch(Exception e) {
} catch (Exception e) {
logger.error("Insert query = " + report.toInsertSQL());
logger.error("Error writing to rpt table", e);
}
}
return status;
}
/**
*
* @return
*/
public boolean purgeTable(int purgeHours) {
public boolean purgeTable(final int purgeHours) {
boolean status = true;
Calendar c = TimeUtil.newGmtCalendar();
c.add(Calendar.HOUR_OF_DAY,-purgeHours);
StringBuilder sb = new StringBuilder("delete from rpt where nominal < ");
sb.append(String.format(HMDBReport.DTFMT, c));
sb.append(";");
String query = sb.toString();
final StringBuilder queryString = new StringBuilder();
try {
logger.debug("Delete query = " + query);
executeNativeSql(query);
} catch(Exception e) {
logger.error("Purge query = " + query);
logger.error("Error in purging hmdb.rpt",e);
txTemplate.execute(new TransactionCallback<Integer>() {
@Override
public Integer doInTransaction(TransactionStatus status) {
Calendar c = TimeUtil.newGmtCalendar();
c.add(Calendar.HOUR_OF_DAY, -purgeHours);
Session sess = getCurrentSession();
Query query = sess
.createSQLQuery("delete from rpt where nominal < :nominal");
query.setCalendar("nominal", c);
queryString.append(query.getQueryString());
return query.executeUpdate();
}
});
} catch (Exception e) {
logger.error("Purge query = " + queryString);
logger.error("Error in purging hmdb.rpt", e);
status = false;
}
return status;
}
}

View file

@ -23,7 +23,9 @@ import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import com.raytheon.uf.common.dataplugin.grid.GridConstants;
@ -47,7 +49,7 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery;
* Jan 11, 2011 mpduff Initial creation
* Mar 28, 2014 2952 mpduff Changed to use UFStatus for logging.
* Apr 21, 2014 2060 njensen Remove dependency on grid dataURI column
*
* Jul 09, 2015 4500 rjpeter Fix SQL Injection concern.
* </pre>
*
* @author mpduff
@ -87,22 +89,20 @@ public class GAFFDB {
*/
public void insertPerflog(String processName, long start)
throws DataAccessLayerException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(start);
String startTime = sdf.format(cal.getTime());
String process = processName;
String sql = "insert into perflog (process, start_time, num_processed, "
+ "num_reads, num_inserts, num_updates, num_deletes, "
+ "elapsed_time, cpu_time, io_time) values ('"
+ process
+ "', " + " '" + startTime + "', 0, 0, 0, 0, 0, 0, 0, 0)";
+ "elapsed_time, cpu_time, io_time) values (:process,"
+ " :startTime, 0, 0, 0, 0, 0, 0, 0, 0)";
Map<String, Object> paramMap = new HashMap<>(2, 1);
paramMap.put("process", processName);
paramMap.put("startTime", cal);
CoreDao dao = null;
dao = new CoreDao(DaoConfig.forDatabase(IHFS));
dao.executeNativeSql(sql, false);
dao.executeSQLUpdate(sql, paramMap);
}
/**
@ -179,7 +179,7 @@ public class GAFFDB {
List<?> rs = dao.queryByCriteria(query);
if ((rs != null) && (!rs.isEmpty())) {
Object result = rs.get(0);
if (result != null && result instanceof GridRecord) {
if ((result != null) && (result instanceof GridRecord)) {
rec = ((GridRecord) result);
}
}
@ -250,37 +250,42 @@ public class GAFFDB {
String sql = "insert into contingencyvalue (lid, pe, dur, ts, "
+ "extremum, probability, validtime, basistime, value, "
+ "shef_qual_code, quality_code, revision, product_id, "
+ "producttime, postingtime) values ('" + areaId + "', "
+ "'PP', " + dur + ", 'CP', 'Z', -1.0, '" + validDate
+ "', '" + basisTime + "', " + avgVal + ", 'Z', "
+ DEFAULT_QC_VALUE + ", " + "0, 'GRIDFFG', '" + validDate
+ "', '" + postDate + "')";
+ "producttime, postingtime) values (:areaId, 'PP', "
+ ":dur, 'CP', 'Z', -1.0, :validDate, :basisTime, :avgVal, "
+ "'Z', :qc, 0, 'GRIDFFG', :validDate, :postDate)";
log.debug(sql);
Map<String, Object> paramMap = new HashMap<>(8, 1);
paramMap.put("areaId", areaId);
paramMap.put("dur", dur);
paramMap.put("validDate", validDate);
paramMap.put("basisTime", basisTime);
paramMap.put("avgVal", avgVal);
paramMap.put("qc", DEFAULT_QC_VALUE);
paramMap.put("validDate", validDate);
paramMap.put("postDate", postDate);
dao.executeNativeSql(sql, false);
dao.executeSQLUpdate(sql, paramMap);
} else {
// Need to do an update to the row
String updateSql = "update contingencyvalue set value = "
+ avgVal
+ ", shef_qual_code = 'Z', quality_code = "
+ DEFAULT_QC_VALUE
+ ", revision = 0, product_id = "
+ "'GRIDFFG', producttime = '"
+ validDate
+ "', "
+ " postingtime = '"
+ postDate
+ "' where "
+ "lid = '"
+ areaId
+ "' and pe = 'PP' and dur = "
+ dur
+ " and ts = 'CP' and extremum = 'Z' and probability = -1.0 "
+ " and validtime = '" + validDate + "' and basistime = '"
+ basisTime + "'";
String updateSql = "update contingencyvalue set value = :avgVal, "
+ "shef_qual_code = 'Z', quality_code = :qc, revision = 0, "
+ "product_id = 'GRIDFFG', producttime = :validDate, "
+ "postingtime = :postDate where lid = :areaId and pe = 'PP' "
+ "and dur = :dur and ts = 'CP' and extremum = 'Z' and probability = -1.0 "
+ " and validtime = :validDate and basistime = :basisTime";
dao.executeSQLUpdate(updateSql);
Map<String, Object> paramMap = new HashMap<>(8, 1);
paramMap.put("avgVal", avgVal);
paramMap.put("qc", DEFAULT_QC_VALUE);
paramMap.put("validDate", validDate);
paramMap.put("postDate", postDate);
paramMap.put("areaId", areaId);
paramMap.put("dur", dur);
paramMap.put("validDate", validDate);
paramMap.put("basisTime", basisTime);
dao.executeSQLUpdate(updateSql, paramMap);
}
}
@ -317,8 +322,8 @@ public class GAFFDB {
public Object[] getLineSegs(String areaId) {
CoreDao dao = null;
dao = new CoreDao(DaoConfig.forDatabase(IHFS));
Object[] rs = dao.executeSQLQuery(LINESEGS_QUERY + " where area_Id = '"
+ areaId + "'");
Object[] rs = dao.executeSQLQuery(LINESEGS_QUERY
+ " where area_Id = :areaId", "areaId", areaId);
return rs;
}

View file

@ -32,8 +32,6 @@ import com.raytheon.uf.common.dataplugin.binlightning.BinLightningRecord;
import com.raytheon.uf.common.dataplugin.binlightning.LightningConstants;
import com.raytheon.uf.common.dataplugin.persist.DefaultPathProvider;
import com.raytheon.uf.common.dataplugin.persist.IPersistable;
import com.raytheon.uf.common.dataquery.db.QueryResult;
import com.raytheon.uf.common.dataquery.db.QueryResultRow;
import com.raytheon.uf.common.datastorage.DataStoreFactory;
import com.raytheon.uf.common.datastorage.IDataStore;
import com.raytheon.uf.common.datastorage.StorageException;
@ -49,26 +47,26 @@ import com.vividsolutions.jts.geom.Coordinate;
/**
* Service implementation for gathering the lightning datasets from files in
* HDF5 format and inserting them into the ifhs lightning table.
*
*
* <pre>
*
*
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jan 06, 2011 5951 jnjanga Initial creation
* Jan 10, 2013 1448 bgonzale Added app context check in runOnSchedule().
* Jan 18, 2013 1469 bkowal Removed the hdf5 data directory.
* Mar 28, 2014 2952 mpduff Changed to use UFStatus for logging.
* Jun 05, 2014 3226 bclement BinLightning refactor
* Aug 20, 2014 3549 njensen Fixed spelling in exceptions
* Sep 17, 2014 3015 bclement improved exception handling
* Dec 04, 2014 3015 njensen Corrected usage of Coordinate(x, y)
* Feb 25, 2015 3992 nabowle Limit getMostRecentStrikes to NLDN.
* Deduplicate lightning data in a
* single BinLightningRecord.
*
* Jan 06, 2011 5951 jnjanga Initial creation
* Jan 10, 2013 1448 bgonzale Added app context check in runOnSchedule().
* Jan 18, 2013 1469 bkowal Removed the hdf5 data directory.
* Mar 28, 2014 2952 mpduff Changed to use UFStatus for logging.
* Jun 05, 2014 3226 bclement BinLightning refactor
* Aug 20, 2014 3549 njensen Fixed spelling in exceptions
* Sep 17, 2014 3015 bclement improved exception handling
* Dec 04, 2014 3015 njensen Corrected usage of Coordinate(x, y)
* Feb 25, 2015 3992 nabowle Limit getMostRecentStrikes to NLDN.
* Deduplicate lightning data in a
* single BinLightningRecord.
* Jul 09, 2015 4500 rjpeter Fix SQL Injection concern.
* </pre>
*
*
* @author jnjanga
* @version 1.0
*/
@ -96,27 +94,30 @@ public class MpeLightningSrv {
/**
* Check the metadata Database for new lightning entries.
*
*
* @return rows returned from the query
*/
private QueryResultRow[] getMostRecentStrikes() throws EdexException {
QueryResult rs = null;
private Object[] getMostRecentStrikes() throws EdexException {
CoreDao coreDao = new CoreDao(DaoConfig.DEFAULT);
/*
* TODO: This can miss data, should use insertTime and track last pull
* time
*/
final String lgtSQL = "select datauri from binlightning "
+ "where reftime > (now()- interval \'30 minutes \')"
+ "and source = '" + LightningConstants.DEFAULT_SOURCE + "'";
+ "and source = :source";
try {
rs = (QueryResult) coreDao.executeNativeSql(lgtSQL, true);
return coreDao.executeSQLQuery(lgtSQL, "source",
LightningConstants.DEFAULT_SOURCE);
} catch (Exception e) {
throw new EdexException("Couldn't get BinLightning records from"
+ " metadata database. Failed SQL: " + lgtSQL, e);
}
return rs.getRows();
}
/**
* Inserts a single record into ihfs's lightning table.
*
*
* @param dataURI
* @throws EdexException
*/
@ -231,48 +232,47 @@ public class MpeLightningSrv {
/**
* Populates ifhs' lightning table with the resultset obtained from querying
* metadata's binlighting table.
*
*
* @param rows
* @throws EdexException
*/
private void ifhsInsertMostRecentStrikes(QueryResultRow[] rows)
private void ifhsInsertMostRecentStrikes(Object[] rows)
throws EdexException {
if (rows.length == 0) {
logger.info("No new lightning records to insert in ifhs. ");
}
for (QueryResultRow row : rows) {
String dataURI = (String) row.getColumn(0);
for (Object col : rows) {
String dataURI = (String) col;
ifhsInsertLightRecord(dataURI);
}
}
/**
* run at scheduled timer.
*
*
* @throws EdexException
*/
public void runOnSchedule() throws EdexException {
if (!AppsDefaults.getInstance().setAppContext(this)) {
return;
}
QueryResultRow[] rows = getMostRecentStrikes();
Object[] rows = getMostRecentStrikes();
ifhsInsertMostRecentStrikes(rows);
}
/**
* Class to simplify deduplicating lightning data in a
* {@link BinLightningRecord} that generate the same ihfs lightning primary
* key.
*/
private static class LightningData {
private short x;
private final short x;
private short y;
private final short y;
private long obstime;
private final long obstime;
private byte strikes;
private final byte strikes;
public LightningData(short x, short y, long time, byte strikes) {
super();
@ -310,7 +310,6 @@ public class MpeLightningSrv {
return strikes;
}
/**
* Generate a hashcode using the ihfs primary key fields: x, y, and
* time.
@ -319,9 +318,9 @@ public class MpeLightningSrv {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (obstime ^ (obstime >>> 32));
result = prime * result + x;
result = prime * result + y;
result = (prime * result) + (int) (obstime ^ (obstime >>> 32));
result = (prime * result) + x;
result = (prime * result) + y;
return result;
}

View file

@ -32,4 +32,5 @@ Require-Bundle: com.raytheon.uf.common.parameter;bundle-version="1.0.0",
org.springframework;bundle-version="2.5.6",
javax.measure;bundle-version="1.0.0",
com.raytheon.uf.common.status;bundle-version="1.12.1174",
com.raytheon.uf.common.comm;bundle-version="1.12.1174"
com.raytheon.uf.common.comm;bundle-version="1.12.1174",
org.hibernate

View file

@ -28,6 +28,11 @@ import java.util.Set;
import javax.measure.converter.UnitConverter;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import com.raytheon.uf.common.dataplugin.PluginDataObject;
import com.raytheon.uf.common.dataplugin.PluginException;
import com.raytheon.uf.common.dataplugin.grid.GridConstants;
@ -37,7 +42,6 @@ import com.raytheon.uf.common.dataplugin.level.Level;
import com.raytheon.uf.common.dataplugin.level.LevelFactory;
import com.raytheon.uf.common.dataplugin.level.MasterLevel;
import com.raytheon.uf.common.dataplugin.persist.IPersistable;
import com.raytheon.uf.common.dataquery.db.QueryResult;
import com.raytheon.uf.common.datastorage.IDataStore;
import com.raytheon.uf.common.datastorage.Request;
import com.raytheon.uf.common.datastorage.StorageException;
@ -70,7 +74,7 @@ import com.raytheon.uf.edex.database.plugin.PluginDao;
* Mar 14, 2013 1587 bsteffen Fix static data persisting to datastore.
* Mar 27, 2013 1821 bsteffen Speed up GridInfoCache.
* Mar 20, 2013 2910 bsteffen Clear dataURI after loading cached info.
*
* Jul 09, 2015 4500 rjpeter Fix SQL Injection concern.
* </pre>
*
* @author bphillip
@ -99,7 +103,7 @@ public class GridDao extends PluginDao {
GridRecord gridRec = (GridRecord) obj;
Object messageData = gridRec.getMessageData();
GridCoverage location = gridRec.getLocation();
if (location != null && messageData instanceof float[]) {
if ((location != null) && (messageData instanceof float[])) {
long[] sizes = new long[] { location.getNx(), location.getNy() };
String abbrev = gridRec.getParameter().getAbbreviation();
String group = gridRec.getDataURI();
@ -109,8 +113,7 @@ public class GridDao extends PluginDao {
datasetName = abbrev;
}
AbstractStorageRecord storageRecord = new FloatDataRecord(
datasetName,
group, (float[]) messageData, 2, sizes);
datasetName, group, (float[]) messageData, 2, sizes);
storageRecord.setCorrelationObject(gridRec);
StorageProperties sp = new StorageProperties();
@ -136,8 +139,8 @@ public class GridDao extends PluginDao {
records.length);
for (PluginDataObject record : records) {
GridRecord rec = (GridRecord) record;
if (rec.getParameter() == null
|| rec.getParameter().getName() == null
if ((rec.getParameter() == null)
|| (rec.getParameter().getName() == null)
|| rec.getParameter().getName().equals("Missing")) {
logger.info("Discarding record due to missing or unknown parameter mapping: "
+ record);
@ -148,7 +151,7 @@ public class GridDao extends PluginDao {
if (level != null) {
MasterLevel ml = level.getMasterLevel();
if (ml != null
if ((ml != null)
&& !LevelFactory.UNKNOWN_LEVEL.equals(ml.getName())) {
validLevel = true;
}
@ -242,7 +245,8 @@ public class GridDao extends PluginDao {
record.setInfo(GridInfoCache.getInstance().getGridInfo(
record.getInfo()));
} catch (DataAccessLayerException e) {
logger.handle(Priority.PROBLEM,
logger.handle(
Priority.PROBLEM,
"Cannot load GridInfoRecord from DB for: "
+ record.getDataURI(), e);
return false;
@ -285,7 +289,8 @@ public class GridDao extends PluginDao {
// // match, but currently we will persist it anyway.
// // result = false;
// } else
if (converter != null && converter != UnitConverter.IDENTITY) {
if ((converter != null)
&& (converter != UnitConverter.IDENTITY)) {
Object messageData = record.getMessageData();
if (messageData instanceof float[]) {
float[] data = (float[]) messageData;
@ -338,7 +343,8 @@ public class GridDao extends PluginDao {
if (level != null) {
MasterLevel ml = level.getMasterLevel();
if (ml != null && !LevelFactory.UNKNOWN_LEVEL.equals(ml.getName())) {
if ((ml != null)
&& !LevelFactory.UNKNOWN_LEVEL.equals(ml.getName())) {
result = true;
}
}
@ -354,60 +360,59 @@ public class GridDao extends PluginDao {
* Overridden to clean up orphan GridInfoRecords.
*/
@Override
public void delete(List<PluginDataObject> objs) {
public void delete(final List<PluginDataObject> objs) {
super.delete(objs);
Set<Integer> orphanedIds = new HashSet<Integer>(objs.size());
StringBuilder sqlString = new StringBuilder(objs.size() * 15 + 80);
sqlString
.append("select distinct info_id from awips.grid where info_id in (");
for (PluginDataObject pdo : objs) {
if (pdo instanceof GridRecord) {
Integer id = ((GridRecord) pdo).getInfo().getId();
if (orphanedIds.add(id)) {
if (orphanedIds.size() > 1) {
sqlString.append(", ");
}
sqlString.append(id);
}
}
}
sqlString.append(");");
try {
QueryResult result = (QueryResult) this.executeNativeSql(sqlString
.toString());
for (int i = 0; i < result.getResultCount(); i++) {
orphanedIds.remove(result.getRowColumnValue(i, 0));
}
if (!orphanedIds.isEmpty()) {
sqlString = new StringBuilder(orphanedIds.size() * 15 + 60);
sqlString.append("delete from awips.grid_info where id in (");
boolean first = true;
for (Integer id : orphanedIds) {
if (!first) {
sqlString.append(", ");
} else {
first = false;
txTemplate.execute(new TransactionCallback<Integer>() {
@Override
public Integer doInTransaction(TransactionStatus status) {
Set<Integer> orphanedIds = new HashSet<Integer>(objs.size());
for (PluginDataObject pdo : objs) {
if (pdo instanceof GridRecord) {
Integer id = ((GridRecord) pdo).getInfo().getId();
orphanedIds.add(id);
}
}
sqlString.append(id);
int rowsDeleted = 0;
if (!orphanedIds.isEmpty()) {
Session sess = getCurrentSession();
Query query = sess
.createQuery("select distinct info.id from GridRecord where info.id in (:ids)");
query.setParameterList("ids", orphanedIds);
List<?> idsToKeep = query.list();
if (idsToKeep != null) {
orphanedIds.removeAll(idsToKeep);
}
if (!orphanedIds.isEmpty()) {
if (purgeModelCacheTopic != null) {
query = sess
.createQuery("delete from GridInfoRecord where id in (:ids)");
query.setParameterList("ids", orphanedIds);
rowsDeleted = query.executeUpdate();
try {
EDEXUtil.getMessageProducer().sendAsyncUri(
purgeModelCacheTopic, orphanedIds);
} catch (EdexException e) {
logger.error(
"Error sending message to purge grid info topic",
e);
}
} else {
GridInfoCache.getInstance().purgeCache(
new ArrayList<Integer>(orphanedIds));
logger.warn("Unable to purge model cache of clustered edices");
}
}
}
return rowsDeleted;
}
sqlString.append(");");
if (purgeModelCacheTopic != null) {
this.executeNativeSql(sqlString.toString());
EDEXUtil.getMessageProducer().sendAsyncUri(
purgeModelCacheTopic, orphanedIds);
} else {
GridInfoCache.getInstance().purgeCache(
new ArrayList<Integer>(orphanedIds));
logger
.warn("Unable to purge model cache of clustered edices");
}
}
} catch (DataAccessLayerException e1) {
logger.error("Error purging orphaned grid info entries", e1);
} catch (EdexException e) {
logger.error(
"Error sending message to purge grid info topic", e);
});
} catch (Exception e) {
logger.error("Error purging orphaned grid info entries", e);
}
}
}

View file

@ -61,7 +61,7 @@ import com.raytheon.uf.edex.ndm.ingest.INationalDatasetSubscriber;
public abstract class AbstractRedbookNdmSubscriber implements
INationalDatasetSubscriber {
protected static final IUFStatusHandler statusHandler = UFStatus
private static final IUFStatusHandler statusHandler = UFStatus
.getHandler(AbstractRedbookNdmSubscriber.class);
/**

View file

@ -59,7 +59,7 @@ import com.raytheon.uf.edex.plugin.redbook.decoder.RedbookFcstMap.MapFcstHr;
*/
public class RedbookNdmMappingSubscriber extends AbstractRedbookNdmSubscriber {
protected static final IUFStatusHandler statusHandler = UFStatus
private static final IUFStatusHandler statusHandler = UFStatus
.getHandler(RedbookNdmMappingSubscriber.class);
private static final String FCST_MAP_FILE_NAME = "redbookFcstMap.xml";

View file

@ -44,8 +44,8 @@ import com.raytheon.uf.edex.plugin.redbook.menu.RedbookNcoMenuUtil;
import com.raytheon.uf.edex.plugin.redbook.menu.RedbookUaMenuUtil;
/**
* This class updates the Redbook menus when Redbook A1 NDM files are dropped
* into EDEX ingest.
* This class updates the Redbook menus when Redbook AWIPS1 NDM files are
* dropped into EDEX ingest.
*
* <pre>
*
@ -57,6 +57,7 @@ import com.raytheon.uf.edex.plugin.redbook.menu.RedbookUaMenuUtil;
* Mar 19, 2015 4310 mpduff Some values must be trimmed.
* Jun 26, 2015 4512 mapeters Renamed from NdmMenuConverter, automatically
* runs and updates menus when A1 files dropped in.
* Jul 14, 2015 4512 mapeters Don't set product buttons' files to null.
*
* </pre>
*
@ -66,7 +67,7 @@ import com.raytheon.uf.edex.plugin.redbook.menu.RedbookUaMenuUtil;
public class RedbookNdmMenuSubscriber extends AbstractRedbookNdmSubscriber {
protected static final IUFStatusHandler statusHandler = UFStatus
private static final IUFStatusHandler statusHandler = UFStatus
.getHandler(RedbookNdmMenuSubscriber.class);
private static final String WMO = "wmo";
@ -95,7 +96,7 @@ public class RedbookNdmMenuSubscriber extends AbstractRedbookNdmSubscriber {
RedbookMenusXML menuXml = new RedbookMenusXML();
MenuEntry titleMenuEntry;
int sepCounter = 0;
List<MenuEntry> subMenuList = new ArrayList<MenuEntry>();
List<MenuEntry> subMenuList = new ArrayList<>();
List<String> menuFileLines = getNdmFileLines(menuFileName);
List<String> dataKeysLines = getNdmFileLines(DATA_KEYS_FILE_NAME);
@ -137,14 +138,18 @@ public class RedbookNdmMenuSubscriber extends AbstractRedbookNdmSubscriber {
} else if (line.startsWith("productButton")) {
String[] parts = line.split(":");
MenuEntry me = new MenuEntry();
me.setFile(null);
/*
* Intentionally don't set MenuEntry's file, as it correctly
* defaults to bundles/Redbook.xml.
*/
me.setType(MenuEntryType.ProductButton);
/*
* There are certain productButtons in the NCO menu data keys in
* the (25000 range) that have data keys that don't map to
* anything. This results in those menu items not being created.
* The site will need to fix this after generating the new
* menus.
* There are certain productButtons in the NCO menu with data
* keys in the (25000 range) and certain productButtons in the
* HPC menu with data keys in the (3313800000 range). These
* don't map to anything, which results in those menu items not
* being created. The site will need to fix this after
* generating the new menus.
*/
String dataKey = parts[1].trim().substring(0, 4);
StringBuilder subValue = new StringBuilder();

View file

@ -50,10 +50,10 @@ public class RedbookCpcMenuUtil extends RedbookMenuUtil {
private static final String MENU_TYPE = NCEP_HYDRO + IPathManager.SEPARATOR
+ "cpc";
/** HPC menu file */
/** CPC menu file */
private static final String CPC_MENU = "cpcMenus.xml";
/** HPC menu file full path */
/** CPC menu file full path */
private static final String MENU_FILE = MENUS + IPathManager.SEPARATOR
+ MENU_TYPE + IPathManager.SEPARATOR + CPC_MENU;

View file

@ -91,8 +91,9 @@ public abstract class RedbookMenuUtil extends AbstractMenuUtil {
* Method called from the RedbookMenuSubscriber when new NDM files are
* placed in /awips2/edex/data/ndm
*
* @param filename
* The file droped into /awips2/edex/data/ndm
* @param xml
* The Redbook menu XML object generated from the file(s) dropped
* into /awips2/edex/data/ndm
*/
public void createMenusFromFile(RedbookMenusXML xml) {
this.xml = xml;

View file

@ -50,10 +50,10 @@ public class RedbookMpcMenuUtil extends RedbookMenuUtil {
private static final String MENU_TYPE = NCEP_HYDRO + IPathManager.SEPARATOR
+ "mpc";
/** HPC menu file */
/** MPC menu file */
private static final String MPC_MENU = "mpcMenus.xml";
/** HPC menu file full path */
/** MPC menu file full path */
private static final String MENU_FILE = MENUS + IPathManager.SEPARATOR
+ MENU_TYPE + IPathManager.SEPARATOR + MPC_MENU;

View file

@ -50,10 +50,10 @@ public class RedbookNcoMenuUtil extends RedbookMenuUtil {
private static final String MENU_TYPE = NCEP_HYDRO + IPathManager.SEPARATOR
+ "nco";
/** HPC menu file */
/** NCO menu file */
private static final String NCO_MENU = "ncoMenus.xml";
/** HPC menu file full path */
/** NCO menu file full path */
private static final String MENU_FILE = MENUS + IPathManager.SEPARATOR
+ MENU_TYPE + IPathManager.SEPARATOR + NCO_MENU;

View file

@ -49,10 +49,10 @@ public class RedbookUaMenuUtil extends RedbookMenuUtil {
/** Menu type constant */
private static final String MENU_TYPE = "upperair";
/** HPC menu file */
/** Upper Air menu file */
private static final String UA_MENU = "uaMenus.xml";
/** HPC menu file full path */
/** Upper Air menu file full path */
private static final String MENU_FILE = MENUS + IPathManager.SEPARATOR
+ MENU_TYPE + IPathManager.SEPARATOR + UA_MENU;

View file

@ -72,6 +72,7 @@ import com.raytheon.openfire.plugin.detailedfeedlog.listener.DetailedFeedLogEven
* and changed error handling to log each bad line.
* Create new DateFormatter for the purge thread.
* Moved presence/site determination out of log method.
* Jul 08, 2015 4316 mapeters Include seconds in message times.
*
* </pre>
*
@ -117,7 +118,7 @@ public class DetailedFeedLogPlugin implements Plugin, PropertyEventListener {
private static final String ROOM_DIR = "Rooms";
private static final String DATE_FORMAT_STR = "MM/dd/yyyy h:mm a";
private static final String DATE_FORMAT_STR = "MM/dd/yyyy h:mm:ss a";
private DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_STR);
@ -195,8 +196,7 @@ public class DetailedFeedLogPlugin implements Plugin, PropertyEventListener {
try {
LogEntry entry = LogEntry.fromString(line, dateFormat);
addToMemoryLog(entry,
file.getName()
.replaceAll(".log", ""));
file.getName().replaceAll(".log", ""));
} catch (ParseException e) {
logger.error("Failed in log " + file.getName()
+ " to parse date from line: " + line, e);
@ -231,8 +231,7 @@ public class DetailedFeedLogPlugin implements Plugin, PropertyEventListener {
* - fqname
* @param message
*/
public static void log(String user, String site, String message,
String room) {
public static void log(String user, String site, String message, String room) {
logger.info("Logging : " + user + " \"" + message + "\"");
Date date = new Date();
LogEntry entry = new LogEntry(date, site, user, message);
@ -245,8 +244,7 @@ public class DetailedFeedLogPlugin implements Plugin, PropertyEventListener {
* @param entry
* @param room
*/
private static void addToMemoryLog(LogEntry entry,
String room) {
private static void addToMemoryLog(LogEntry entry, String room) {
Queue<LogEntry> queue = null;
if (entries.containsKey(room)) {
queue = entries.get(room);
@ -311,7 +309,7 @@ public class DetailedFeedLogPlugin implements Plugin, PropertyEventListener {
- (purgeLogTime * SECONDS_TO_MILLIS));
// DateFormat for this thread
DateFormat dateFormat = new SimpleDateFormat(
"MM/dd/yyyy h:mm a");
"MM/dd/yyyy h:mm:ss a");
String dateText = dateFormat.format(latestTimeToKeep);
logger.info("Purging the log of anything before "
+ dateText);
@ -350,6 +348,7 @@ public class DetailedFeedLogPlugin implements Plugin, PropertyEventListener {
return entries.get(room);
}
@Override
public void propertyDeleted(String arg0, Map<String, Object> arg1) {
// do nothing, as we want to keep the current properties if some are
// deleted

View file

@ -62,7 +62,7 @@ EDEX_BANNER_TXT=
# 11.6.X builds.
function updateCAVEVersionLegacy()
{
local TMP_PRODUCTS_DIR="/awips2/cave/.tmp/products"
local TMP_PRODUCTS_DIR="/awips2/${AWIPS_PRODUCT}/.tmp/products"
cd ${TMP_PRODUCTS_DIR}
# update plugin.xml
@ -100,9 +100,9 @@ function padEdexBannerLine()
return 0
}
function updateCAVEVersion()
function updateVersion()
{
local TMP_PRODUCTS_DIR="/awips2/cave/.tmp/products"
local TMP_PRODUCTS_DIR="/awips2/${AWIPS_PRODUCT}/.tmp/products"
if [ -d ${TMP_PRODUCTS_DIR} ]; then
rm -rf ${TMP_PRODUCTS_DIR}
@ -126,7 +126,7 @@ function updateCAVEVersion()
ARCH="x86"
# Determine the architecture.
TMP=`file /awips2/cave/cave | grep "ELF 64-bit"`
TMP=`file /awips2/${AWIPS_PRODUCT}/${AWIPS_PRODUCT} | grep "ELF 64-bit"`
if [ ! "${TMP}" = "" ]; then
ARCH="x86_64"
fi
@ -143,15 +143,17 @@ function updateCAVEVersion()
echo "\\tBUILD DATE: %{_component_build_date}\\n\\" \
>> plugin.properties
echo "\\tBUILD TIME: %{_component_build_time}\\n\\" >> plugin.properties
echo "\\tBUILD SYSTEM: %{_component_build_system}\\n\\" \
echo "\\tBUILD SYSTEM: %{_component_build_system}\\n" \
>> plugin.properties
echo "caveVersion=%{_component_version}-%{_component_release}" \
>> plugin.properties
# Update the jar file.
/awips2/java/bin/jar uf ${AWIPS_PRODUCT_JAR} plugin.properties
# Relocate the jar file.
mv ${AWIPS_PRODUCT_JAR} /awips2/cave/plugins
mv ${AWIPS_PRODUCT_JAR} /awips2/${AWIPS_PRODUCT}/plugins
rm -rf ${TMP_PRODUCTS_DIR}
return 0
}
@ -184,7 +186,22 @@ if [ -d /awips2/cave/plugins ]; then
if [ ${RC} -eq 0 ]; then
# does the jar exist?
if [ -f ${AWIPS_PRODUCT_JAR} ]; then
updateCAVEVersion
AWIPS_PRODUCT="cave"
updateVersion
fi
fi
fi
AWIPS_PRODUCT_WILDCARD="/awips2/alertviz/plugins/com.raytheon.uf.viz.product.alertviz_*.jar"
# Get the actual name of the product jar.
if [ -d /awips2/alertviz/plugins ]; then
AWIPS_PRODUCT_JAR=`ls -1 ${AWIPS_PRODUCT_WILDCARD}`
RC=$?
if [ ${RC} -eq 0 ]; then
# does the jar exist?
if [ -f ${AWIPS_PRODUCT_JAR} ]; then
AWIPS_PRODUCT="alertviz"
updateVersion
fi
fi
fi

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