Unnamed: 0
int64 0
2.05k
| func
stringlengths 27
124k
| target
bool 2
classes | project
stringlengths 39
117
|
---|---|---|---|
500 | SwingUtilities.invokeLater(new Runnable() {
public void run() {
openNewMulti(name, multi);
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_enums_PlaceObjectsInMultiAction.java |
501 | public class PlaceObjectsInMultiActionTest {
@Mock
private AbstractComponent componentA, componentB;
@Mock
private AbstractComponent multi;
@Mock
private View viewManifestation1, viewManifestation2;
@Mock
private ActionContext ac;
private ArrayList<View> selected;
@Mock
private FeedProvider feed;
@Mock
private Platform mockPlatform;
@Mock
private PersistenceProvider mockPersistence;
private PlaceObjectsInMultiAction action;
private int success, fail;
private Collection<AbstractComponent> sourceComponents;
private boolean setResult;
@SuppressWarnings("serial")
@BeforeTest
public void setup() {
MockitoAnnotations.initMocks(this);
action = new PlaceObjectsInMultiAction() {
@Override
protected String getNewMulti(Collection<AbstractComponent> sourceComponents) {
PlaceObjectsInMultiActionTest.this.sourceComponents = sourceComponents;
return "test";
}
@Override
AbstractComponent createNewMulti(Collection<AbstractComponent> sourceComponents) {
return setResult ? multi : null;
}
@Override
void openNewMulti(String name, AbstractComponent collection) {
success++;
}
@Override
void showErrorInCreateMulti() {
fail++;
}
};
Mockito.when(viewManifestation1.getManifestedComponent()).thenReturn(componentA);
Mockito.when(viewManifestation2.getManifestedComponent()).thenReturn(componentB);
Mockito.when(componentA.getCapability(FeedProvider.class)).thenReturn(feed);
Mockito.when(componentB.getCapability(FeedProvider.class)).thenReturn(feed);
selected = new ArrayList<View> ();
selected.add(viewManifestation1);
selected.add(viewManifestation2);
Mockito.when(ac.getSelectedManifestations()).thenReturn(selected);
Mockito.when(ac.getSelectedManifestations()).thenReturn(selected);
Mockito.when(mockPlatform.getPersistenceProvider()).thenReturn(mockPersistence);
new PlatformAccess().setPlatform(mockPlatform);
}
@AfterTest
public void teardown() {
new PlatformAccess().setPlatform(mockPlatform);
}
@Test
public void testCanHandle() {
Assert.assertTrue(action.canHandle(ac));
}
@Test (dependsOnMethods = {"testCanHandle"})
public void testIsEnabled() {
Assert.assertTrue(action.isEnabled());
}
@Test(dependsOnMethods = {"testIsEnabled"})
public void testActionPerformedSuccessfulCase() throws Exception {
reset();
setResult = true;
action.actionPerformed(new ActionEvent(viewManifestation1, 0, ""));
final Semaphore s = new Semaphore(1);
s.acquire();
// since the action will be invoked later, dispatch this on the AWT thread to make sure
// the action has already been delegated
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
s.release();
}
});
s.tryAcquire(5, TimeUnit.SECONDS);
Assert.assertEquals(success, 1);
Assert.assertEquals(fail, 0);
Assert.assertNotNull(sourceComponents);
Assert.assertEquals(sourceComponents.size(), 2);
Assert.assertTrue(sourceComponents.contains(componentA));
Assert.assertTrue(sourceComponents.contains(componentB));
}
@Test(dependsOnMethods = {"testIsEnabled"})
public void testActionPerformedFailedCase() {
reset();
setResult = false;
action.actionPerformed(new ActionEvent(viewManifestation1, 0,""));
Assert.assertEquals(success,0);
Assert.assertEquals(fail,1);
Assert.assertEquals(sourceComponents.size(), 2);
}
private void reset(){
success = fail = 0;
sourceComponents = null;
}
} | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_enums_PlaceObjectsInMultiActionTest.java |
502 | action = new PlaceObjectsInMultiAction() {
@Override
protected String getNewMulti(Collection<AbstractComponent> sourceComponents) {
PlaceObjectsInMultiActionTest.this.sourceComponents = sourceComponents;
return "test";
}
@Override
AbstractComponent createNewMulti(Collection<AbstractComponent> sourceComponents) {
return setResult ? multi : null;
}
@Override
void openNewMulti(String name, AbstractComponent collection) {
success++;
}
@Override
void showErrorInCreateMulti() {
fail++;
}
}; | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_enums_PlaceObjectsInMultiActionTest.java |
503 | SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
s.release();
}
}); | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_enums_PlaceObjectsInMultiActionTest.java |
504 | @SuppressWarnings("serial")
public class PlaceObjectsInMultiDialog extends JDialog {
private static ResourceBundle bundle = ResourceBundle.getBundle("MultiComponent");
private static final int ICON_HEIGHT = 16;
private static final int ICON_WIDTH = 16;
private static final int DIALOG_HEIGHT = 225;
private static final int DIALOG_WIDTH = 600;
private static final int MIN_LENGTH = 1;
private static final int MAX_LENGTH = 300;
private static final int COL_SIZE = 30;
private static String errorMessage;
static {
errorMessage = "Multi name must contain" + " " + MIN_LENGTH
+ " to " + MAX_LENGTH + " characters.";
}
private boolean confirmed = false;
private final JLabel message = new JLabel();
private final JTextField name = new JTextField();
private final JButton create = new JButton();
/**
* Place multi objects in new collection dialog window.
* @param frame the Frame.
* @param selectedComponentNames selective component names.
*/
public PlaceObjectsInMultiDialog(Frame frame, String [] selectedComponentNames) {
super(frame, ModalityType.DOCUMENT_MODAL);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle("Place Objects in New Multi" + " - " + frame.getTitle());
JLabel prompt = new JLabel(bundle.getString("DialogPrompt"));
name.setText("untitled Multi");
name.selectAll();
name.setColumns(COL_SIZE);
name.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
}
@Override
public void insertUpdate(DocumentEvent e) {
doAction();
}
@Override
public void removeUpdate(DocumentEvent e) {
doAction();
}
private boolean verify(String input) {
return DataValidation.validateLength(input, MIN_LENGTH, MAX_LENGTH);
}
private void doAction() {
boolean flag = verify(name.getText().trim());
create.setEnabled(flag);
message.setIcon((flag) ? null : MCTIcons.getErrorIcon(ICON_WIDTH, ICON_HEIGHT));
message.setText((flag) ? "" : errorMessage);
}
});
name.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
name.setForeground(Color.BLACK);
}
});
//Control panel for creating or canceling out of the creation window
JPanel controlPanel = new JPanel();
//Create button for creation window
create.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
PlaceObjectsInMultiDialog.this.setVisible(false);
PlaceObjectsInMultiDialog.this.dispose();
confirmed = true;
}
});
create.setText(bundle.getString("Create"));
create.setName("createButton");
//Cancel button for creation window
JButton cancel = new JButton(bundle.getString("Cancel"));
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PlaceObjectsInMultiDialog.this.dispose();
}
});
cancel.setName("cancelButton");
controlPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
controlPanel.add(create);
controlPanel.add(cancel);
//Displays what telemetry elements are associated with the new multi
JPanel messagePanel = new JPanel();
messagePanel.add(message);
JLabel titleLabel = new JLabel(bundle.getString("TitleLabel"));
JTextArea textArea = new JTextArea();
textArea.setBorder(BorderFactory.createEmptyBorder());
textArea.setBackground(LafColor.MENUBAR_BACKGROUND);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
textArea.setEditable(false);
String newLine = "\n";
String space = " ";
for (String name : selectedComponentNames)
textArea.append('\u2022' + space + name + newLine);
textArea.setCaretPosition(0);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10, 10, 0, 0);
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridy = 0;
c.weightx = 0.01;
add(prompt, c);
c.gridx = 1;
c.weightx = 0.99;
c.insets = new Insets(10, 0, 0, 10);
add(name, c);
c.gridx = 0;
c.gridy = 1;
c.weightx = 1;
c.gridwidth = 2;
c.insets = new Insets(0, 10, 0, 10);
add(messagePanel, c);
c.gridy = 2;
c.insets = new Insets(0, 10, 10, 10);
add(titleLabel, c);
c.gridy = 3;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
add(scrollPane, c);
c.gridy = 4;
c.insets = new Insets(0, 0, 0, 5);
c.anchor = GridBagConstraints.LAST_LINE_END;
c.fill = GridBagConstraints.HORIZONTAL;
add(controlPanel, c);
//Set Create button as default to respond to enter key
this.getRootPane().setDefaultButton(create);
setSize(DIALOG_WIDTH,DIALOG_HEIGHT);
setLocationRelativeTo(frame);
setVisible(true);
}
/**
* Gets the confirmed multi name.
* @return the multi name.
*/
public String getConfirmedMultiName() {
if (confirmed)
return name.getText().trim();
else
return "";
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_enums_PlaceObjectsInMultiDialog.java |
505 | name.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
}
@Override
public void insertUpdate(DocumentEvent e) {
doAction();
}
@Override
public void removeUpdate(DocumentEvent e) {
doAction();
}
private boolean verify(String input) {
return DataValidation.validateLength(input, MIN_LENGTH, MAX_LENGTH);
}
private void doAction() {
boolean flag = verify(name.getText().trim());
create.setEnabled(flag);
message.setIcon((flag) ? null : MCTIcons.getErrorIcon(ICON_WIDTH, ICON_HEIGHT));
message.setText((flag) ? "" : errorMessage);
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_enums_PlaceObjectsInMultiDialog.java |
506 | name.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
name.setForeground(Color.BLACK);
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_enums_PlaceObjectsInMultiDialog.java |
507 | create.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
PlaceObjectsInMultiDialog.this.setVisible(false);
PlaceObjectsInMultiDialog.this.dispose();
confirmed = true;
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_enums_PlaceObjectsInMultiDialog.java |
508 | cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PlaceObjectsInMultiDialog.this.dispose();
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_enums_PlaceObjectsInMultiDialog.java |
509 | public class Expression {
private String operator;
private Double val= Double.valueOf(0);
private String display;
/**
* Expression default initialization constructor.
*/
public Expression() {
this.operator = "=";
this.display = "";
}
/**
* Expression initialization based upon operation, value, and display.
* @param op operation.
* @param val value.
* @param dis display name.
*/
public Expression(String op, String val, String dis){
this.operator = op;
if (val != null) {
try {
this.val = Double.parseDouble(val);
} catch (NumberFormatException nfe) {
// ignore the default value of zero will be used
}
}
this.display = dis;
}
/**
* Sets the operator.
* @param op operation.
*/
public void setOperator(String op) {
this.operator = op;
}
/**
* Sets the operator.
* @return operator the operator.
*/
public String getOperator() {
return this.operator;
}
/**
* Sets the value.
* @param val the value.
*/
public void setVal(Double val) {
this.val = val;
}
/**
* Gets the value.
* @return val the value.
*/
public Double getVal() {
return this.val;
}
/**
* Sets the display name.
* @param display name.
*/
public void setDisplay(String display) {
this.display = display;
}
/**
* Gets the display name.
* @return display name.
*/
public String getDisplay() {
return this.display;
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_Expression.java |
510 | public class ExpressionList {
private ArrayList <Expression> expList;
/**
* Expression list constructor.
* @param code the code.
*/
public ExpressionList(String code) {
expList = compile(code);
}
/**
* Compiles the expression.
* @param code the code.
* @return array list of expressions.
*/
public ArrayList <Expression> compile(String code){
ArrayList <Expression> expressions = new ArrayList <Expression> ();
Matcher m = EnumEvaluator.enumExpression.matcher(code);
while (m.find()){
assert m.groupCount() == 3 : "only three matching groups should be discovered: found " + m.groupCount();
String relation = m.group(1);
String value = m.group(2);
String display = m.group(3);
expressions.add(new Expression(relation, value, display));
}
return expressions;
}
/**
* Gets the size of the expression list.
* @return the size number.
*/
public int size() {
return expList.size();
}
/**
* Gets the index of the expression.
* @param exp expression.
* @return index number.
*/
public int indexOf (Expression exp) {
return expList.indexOf(exp);
}
/**
* Gets the expression based on the index.
* @param index number.
* @return expression.
*/
public Expression getExp (int index) {
return expList.get(index);
}
/**
* Adds the expression to the list.
* @param exp expression.
*/
public void addExp (Expression exp) {
expList.add(exp);
}
/**
* Adds the expression to the list based on the index number and expression object.
* @param index number.
* @param exp expression object.
*/
public void addExp (int index, Expression exp) {
expList.add(index, exp);
}
/**
* Deletes the expression.
* @param exp expression.
*/
public void deleteExp (Expression exp) {
int index;
if (expList != null && expList.contains(exp)) {
index = expList.indexOf(exp);
expList.remove(index);
}
}
/**
* Moves the expression.
* @param moveTo index.
* @param expSelected selected expression.
*/
public void move (int moveTo, Expression expSelected) {
Expression temp = expSelected;
int currentIndex;
if (expList.contains(expSelected)){
currentIndex = expList.indexOf(expSelected);
//case for moving to bottom
if (moveTo == expList.size()-1){
expList.remove(currentIndex);
expList.add(temp);
}
else {
expList.remove(currentIndex);
expList.add(moveTo, temp);
}
}
}
@Override
public String toString(){
String expressions = "";
Expression temp;
String exp;
for (int i = 0; i < expList.size(); i++){
temp = expList.get(i);
exp = temp.getOperator() + " " + temp.getVal() + " " + temp.getDisplay() + " |";
expressions += exp;
}
return expressions;
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionList.java |
511 | public class ExpressionTest {
@Test
public void testExpression() {
Expression e = new Expression("=", "abc", "d");
Assert.assertEquals(e.getVal(), Double.valueOf(0));
}
@Test
public void testMultiRuleExpression() {
MultiRuleExpression e = new MultiRuleExpression(SetLogic.ALL_PARAMETERS, new String[] {"PUI1","PUI2"},
"PUI1","=", "abc", "display", "rule1");
Assert.assertEquals(e.getVal(), Double.valueOf(0));
}
} | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionTest.java |
512 | public class ExpressionsFormattingController {
private ExpressionsFormattingController() {
}
/**
* Notifies that a new expression has been created.
* @param newExp the new expression to add.
* @param expList the expression list to add.
*/
public static void notifyExpressionAdded(Expression newExp, ExpressionList expList){
if (expList != null) {
expList.addExp(newExp);
}
}
/**
* Notifies the an existing expression has been deleted.
* @param selectedExp the selected expression to delete.
* @param expList the expression list to delete.
*/
public static void notifyExpressionDeleted(Expression selectedExp, ExpressionList expList){
if (selectedExp != null && expList != null){
expList.deleteExp(selectedExp);
}
}
/**
* Notifies that an existing expression has been added on top.
* @param newExp the new expression to add above.
* @param selectedExp the selected expression to add from.
* @param expList the expression list to add to.
*/
public static void notifyExpressionAddedAbove(Expression newExp, Expression selectedExp, ExpressionList expList){
if (newExp != null && selectedExp != null && expList != null) {
int index = expList.indexOf(selectedExp);
expList.addExp(index, newExp);
}
}
/**
* Notifies than an existing expression has been added below.
* @param newExp the new expression to add below.
* @param selectedExp the selected expression to add to.
* @param expList the expression list to add to.
*/
public static void notifyExpressionAddedBelow(Expression newExp, Expression selectedExp, ExpressionList expList){
if (newExp != null && selectedExp != null && expList != null) {
int index = expList.indexOf(selectedExp);
expList.addExp(index+1, newExp);
}
}
/**
* Notifies to move expression up one.
* @param exp the expression to move up one.
* @param expList the expression list.
*/
public static void notifyMovedUpOne(Expression exp, ExpressionList expList){
if (exp != null && expList != null){
int index = expList.indexOf(exp);
expList.move(index-1, exp);
}
}
/**
* Notifies to move expression down one.
* @param exp the expression to move down one.
* @param expList the expression list.
*/
public static void notifyMovedDownOne(Expression exp, ExpressionList expList){
if (exp != null && expList != null){
int index = expList.indexOf(exp);
expList.move(index+1, exp);
}
}
/**
* Notifies to move expression to top level.
* @param exp the expression to move to top level.
* @param expList the expression list.
*/
public static void notifyMoveToTop(Expression exp, ExpressionList expList){
if (exp != null && expList != null){
expList.move(0, exp);
}
}
/**
* Notifies to move expression to the bottom level.
* @param exp the expression to move expression to the bottom level.
* @param expList the expression list.
*/
public static void notifyMoveToBottom(Expression exp, ExpressionList expList){
if (exp != null && expList != null){
expList.move(expList.size()-1, exp);
}
}
/**
* Notifies to remove telemetry item from the expression.
* @param telem the telemetry component.
* @param telemList the array list of telemetry components.
*/
public static void notifyRemoveTelem(AbstractComponent telem, ArrayList<AbstractComponent> telemList) {
int index = telemList.indexOf(telem);
telemList.remove(index);
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingController.java |
513 | public class ExpressionsFormattingControllerTest {
private Expression e1, e2, e3;
private ExpressionList eList;
private ArrayList<AbstractComponent> tList;
@Mock
private AbstractComponent t;
@BeforeMethod
public void setup(){
MockitoAnnotations.initMocks(this);
eList = new ExpressionList("");
e1 = new Expression("=", "1", "test1");
e2 = new Expression("=", "2", "test2");
e3 = new Expression("=", "3", "test3");
tList = new ArrayList<AbstractComponent>();
}
@AfterMethod
public void tearDown() {
this.eList = new ExpressionList("");
}
@Test
public void notifyExpressionAddedTest(){
ExpressionsFormattingController.notifyExpressionAdded(e1, eList);
Assert.assertEquals(eList.size(), 1);
Assert.assertEquals(eList.getExp(0), e1);
}
@Test
public void notifyExpressionDeletedTest(){
eList.addExp(e1);
eList.addExp(e2);
ExpressionsFormattingController.notifyExpressionDeleted(e2, eList);
Assert.assertEquals(eList.size(), 1);
Assert.assertEquals(eList.getExp(0), e1);
}
@Test
public void notifyExpressionAddedAboveTest(){
eList.addExp(e1);
ExpressionsFormattingController.notifyExpressionAddedAbove(e2, e1, eList);
Assert.assertEquals(eList.size(), 2);
Assert.assertEquals(eList.getExp(0), e2);
}
@Test
public void notifyExpressionAddedBelowTest(){
eList.addExp(e1);
ExpressionsFormattingController.notifyExpressionAddedBelow(e2, e1, eList);
Assert.assertEquals(eList.size(), 2);
Assert.assertEquals(eList.getExp(0), e1);
}
@Test
public void notifyMovedUpOneTest(){
eList.addExp(e1);
eList.addExp(e2);
ExpressionsFormattingController.notifyMovedUpOne(e2, eList);
Assert.assertEquals(eList.getExp(0), e2);
}
@Test
public void notifyMovedDownOneTest(){
eList.addExp(e1);
eList.addExp(e2);
ExpressionsFormattingController.notifyMovedDownOne(e1, eList);
Assert.assertEquals(eList.getExp(0), e2);
}
@Test
public void notifyMoveToTopTest(){
eList.addExp(e1);
eList.addExp(e2);
eList.addExp(e3);
ExpressionsFormattingController.notifyMoveToTop(e3, eList);
Assert.assertEquals(eList.getExp(0), e3);
}
@Test
public void notifyMoveToBottomTest(){
eList.addExp(e1);
eList.addExp(e2);
eList.addExp(e3);
ExpressionsFormattingController.notifyMoveToBottom(e1, eList);
Assert.assertEquals(eList.getExp(2), e1);
Assert.assertEquals(eList.getExp(0), e2);
}
@Test
public void notifyRemoveTelemTest(){
tList.add(t);
Assert.assertEquals(tList.size(), 1);
ExpressionsFormattingController.notifyRemoveTelem(t, tList);
Assert.assertEquals(tList.size(), 0);
}
} | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControllerTest.java |
514 | @SuppressWarnings("serial")
public class ExpressionsFormattingControlsPanel extends JPanel{
private static final ResourceBundle bundle = ResourceBundle.getBundle("Enumerator");
//Creation Panel
private JButton addExpButton = null;
private JButton deleteExpButton = null;
private JButton addAboveButton = null;
private JButton addBelowButton = null;
//Expression Order Editing Panel
private JButton upOneButton = null;
private JButton downOneButton = null;
private JButton upTopButton = null;
private JButton downBottomButton = null;
//Telemetry Association Editing Panel
private JButton deleteTelemButton = null;
private boolean listenersEnabled = true;
private final ExpressionsViewManifestation managedExpression;
/**
* Initialize the expressions format control panel.
* @param managedExpression the view manifestation.
*/
ExpressionsFormattingControlsPanel (ExpressionsViewManifestation managedExpression) {
this.managedExpression = managedExpression;
createExpressionsFormattingControlsPanel();
}
private void createExpressionsFormattingControlsPanel() {
JPanel controlPanel = new JPanel (new GridBagLayout());
JPanel creationPanel = createCreationPanel();
JPanel orderingPanel = createOrderingPanel();
JPanel telemetryPanel = createTelemetryPanel();
//Creation Panel
GridBagConstraints creationPanelConstraints = new GridBagConstraints();
creationPanelConstraints.fill = GridBagConstraints.NONE;
creationPanelConstraints.anchor = GridBagConstraints.NORTHWEST;
creationPanelConstraints.weighty = 0;
creationPanelConstraints.weightx = 1;
creationPanelConstraints.insets = new Insets(3,7,3,7);
creationPanelConstraints.gridx = 0;
creationPanelConstraints.gridy = 0;
controlPanel.add(creationPanel, creationPanelConstraints);
//Ordering Panel
GridBagConstraints orderingPanelConstraints = new GridBagConstraints();
orderingPanelConstraints.fill = GridBagConstraints.NONE;
orderingPanelConstraints.anchor = GridBagConstraints.NORTHWEST;
orderingPanelConstraints.weighty = 0;
orderingPanelConstraints.weightx = 1;
orderingPanelConstraints.insets = new Insets(3,7,3,7);
orderingPanelConstraints.gridx = 0;
orderingPanelConstraints.gridy = 1;
controlPanel.add(orderingPanel, orderingPanelConstraints);
//Telemetry Panel
GridBagConstraints telemetryPanelConstraints = new GridBagConstraints();
telemetryPanelConstraints.fill = GridBagConstraints.NONE;
telemetryPanelConstraints.anchor = GridBagConstraints.NORTHWEST;
telemetryPanelConstraints.weighty = 1;
telemetryPanelConstraints.weightx = 1;
telemetryPanelConstraints.insets = new Insets(3,7,3,7);
telemetryPanelConstraints.gridx = 0;
telemetryPanelConstraints.gridy = 2;
controlPanel.add(telemetryPanel, telemetryPanelConstraints);
controlPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
this.setLayout(new GridLayout(1,0));
this.add(controlPanel);
}
private JPanel createCreationPanel() {
JPanel creationPanel = new JPanel();
creationPanel.setLayout(new BorderLayout());
//Add title
creationPanel.setBorder(BorderFactory.createTitledBorder(bundle.getString("CreateDeleteTitle")));
JPanel creationInnerPanel = new JPanel();
creationPanel.add(creationInnerPanel, BorderLayout.WEST);
creationInnerPanel.setLayout(new GridBagLayout());
//Creation controls
addExpButton = new JButton(bundle.getString("AddExpressionTitle"));
deleteExpButton = new JButton(bundle.getString("DeleteExpressionTitle"));
addAboveButton = new JButton(bundle.getString("AddAboveTitle"));
addBelowButton = new JButton(bundle.getString("AddBelowTitle"));
addExpButton.setName(bundle.getString("AddExpressionTitle"));
deleteExpButton.setName(bundle.getString("DeleteExpressionTitle"));
addAboveButton.setName(bundle.getString("AddAboveTitle"));
addBelowButton.setName(bundle.getString("AddBelowTitle"));
addExpButton.setToolTipText(bundle.getString("AddExpressionToolTip"));
deleteExpButton.setToolTipText(bundle.getString("DeleteExpressionToolTip"));
addAboveButton.setToolTipText(bundle.getString("AddAboveToolTip"));
addBelowButton.setToolTipText(bundle.getString("AddBelowToolTip"));
addExpButton.setOpaque(false);
deleteExpButton.setOpaque(false);
addAboveButton.setOpaque(false);
addBelowButton.setOpaque(false);
addExpButton.setFocusPainted(false);
deleteExpButton.setFocusPainted(false);
addAboveButton.setFocusPainted(false);
addBelowButton.setFocusPainted(false);
addExpButton.setSize(200,200);
addExpButton.setContentAreaFilled(true);
deleteExpButton.setSize(200,200);
deleteExpButton.setContentAreaFilled(true);
addAboveButton.setSize(200,200);
addAboveButton.setContentAreaFilled(true);
addBelowButton.setSize(200,200);
addBelowButton.setContentAreaFilled(true);
addExpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listenersEnabled){
ExpressionsFormattingController.notifyExpressionAdded(new Expression(), managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
});
deleteExpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyExpressionDeleted(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
});
addAboveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyExpressionAddedAbove(new Expression(), selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
});
addBelowButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyExpressionAddedBelow(new Expression(), selectedExpression, managedExpression.getExpressions());
managedExpression.fireFocusPersist();
}
}
});
GridBagConstraints addExpButtonConstraints = new GridBagConstraints();
addExpButtonConstraints.fill = GridBagConstraints.NONE;
addExpButtonConstraints.anchor = GridBagConstraints.LINE_START;
addExpButtonConstraints.weighty = 1;
addExpButtonConstraints.weightx = 0;
addExpButtonConstraints.ipadx = 1;
addExpButtonConstraints.gridx = 0;
addExpButtonConstraints.gridy = 0;
creationInnerPanel.add(addExpButton, addExpButtonConstraints);
GridBagConstraints deleteExpButtonConstraints = new GridBagConstraints();
deleteExpButtonConstraints.fill = GridBagConstraints.NONE;
deleteExpButtonConstraints.anchor = GridBagConstraints.LINE_START;
deleteExpButtonConstraints.weighty = 1;
deleteExpButtonConstraints.weightx = 0;
deleteExpButtonConstraints.ipadx = 1;
deleteExpButtonConstraints.gridx = 1;
deleteExpButtonConstraints.gridy = 0;
creationInnerPanel.add(deleteExpButton, deleteExpButtonConstraints);
GridBagConstraints addAboveButtonConstraints = new GridBagConstraints();
addAboveButtonConstraints.fill = GridBagConstraints.NONE;
addAboveButtonConstraints.anchor = GridBagConstraints.LINE_START;
addAboveButtonConstraints.weighty = 1;
addAboveButtonConstraints.weightx = 0;
addAboveButtonConstraints.ipadx = 1;
addAboveButtonConstraints.gridx = 2;
addAboveButtonConstraints.gridy = 0;
creationInnerPanel.add(addAboveButton, addAboveButtonConstraints);
GridBagConstraints addBelowButtonConstraints = new GridBagConstraints();
addBelowButtonConstraints.fill = GridBagConstraints.NONE;
addBelowButtonConstraints.anchor = GridBagConstraints.LINE_START;
addBelowButtonConstraints.weighty = 1;
addBelowButtonConstraints.weightx = 1;
addBelowButtonConstraints.ipadx = 1;
addBelowButtonConstraints.gridx = 3;
addBelowButtonConstraints.gridy = 0;
creationInnerPanel.add(addBelowButton, addBelowButtonConstraints);
return creationPanel;
}
private JPanel createOrderingPanel() {
JPanel orderingPanel = new JPanel();
orderingPanel.setLayout(new BorderLayout());
//Add title
orderingPanel.setBorder(BorderFactory.createTitledBorder(bundle.getString("EditOrderTitle")));
JPanel orderingInnerPanel = new JPanel();
orderingPanel.add(orderingInnerPanel, BorderLayout.WEST);
orderingInnerPanel.setLayout(new GridBagLayout());
upOneButton = new JButton(bundle.getString("MoveUpOneTitle"));
downOneButton = new JButton(bundle.getString("MoveDownOneTitle"));
upTopButton = new JButton(bundle.getString("MoveToTopTitle"));
downBottomButton = new JButton(bundle.getString("MoveToBottomTitle"));
upOneButton.setName(bundle.getString("MoveUpOneTitle"));
downOneButton.setName(bundle.getString("MoveDownOneTitle"));
upTopButton.setName(bundle.getString("MoveToTopTitle"));
downBottomButton.setName(bundle.getString("MoveToBottomTitle"));
upOneButton.setToolTipText(bundle.getString("MoveUpOneToolTip"));
downOneButton.setToolTipText(bundle.getString("MoveDownOneToolTip"));
upTopButton.setToolTipText(bundle.getString("MoveToTopToolTip"));
downBottomButton.setToolTipText(bundle.getString("MoveToBottomToolTip"));
upOneButton.setOpaque(false);
downOneButton.setOpaque(false);
upTopButton.setOpaque(false);
downBottomButton.setOpaque(false);
upOneButton.setFocusPainted(false);
downOneButton.setFocusPainted(false);
upTopButton.setFocusPainted(false);
downBottomButton.setFocusPainted(false);
upOneButton.setSize(400,10);
upOneButton.setContentAreaFilled(true);
downOneButton.setSize(400,10);
downOneButton.setContentAreaFilled(true);
upTopButton.setSize(400,10);
upTopButton.setContentAreaFilled(true);
downBottomButton.setSize(400,10);
downBottomButton.setContentAreaFilled(true);
upOneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyMovedUpOne(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
});
downOneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyMovedDownOne(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
});
upTopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyMoveToTop(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
});
downBottomButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyMoveToBottom(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
});
GridBagConstraints upOneButtonConstraints = new GridBagConstraints();
upOneButtonConstraints.fill = GridBagConstraints.NONE;
upOneButtonConstraints.anchor = GridBagConstraints.LINE_START;
upOneButtonConstraints.weighty = 1;
upOneButtonConstraints.ipadx = 1;
upOneButtonConstraints.gridx = 0;
upOneButtonConstraints.gridy = 0;
orderingInnerPanel.add(upOneButton, upOneButtonConstraints);
GridBagConstraints downOneButtonConstraints = new GridBagConstraints();
downOneButtonConstraints.fill = GridBagConstraints.NONE;
downOneButtonConstraints.anchor = GridBagConstraints.LINE_START;
downOneButtonConstraints.weighty = 1;
downOneButtonConstraints.ipadx = 1;
downOneButtonConstraints.gridx = 1;
downOneButtonConstraints.gridy = 0;
orderingInnerPanel.add(downOneButton, downOneButtonConstraints);
GridBagConstraints upTopButtonConstraints = new GridBagConstraints();
upTopButtonConstraints.fill = GridBagConstraints.NONE;
upTopButtonConstraints.anchor = GridBagConstraints.LINE_START;
upTopButtonConstraints.weighty = 1;
upTopButtonConstraints.ipadx = 1;
upTopButtonConstraints.gridx = 2;
upTopButtonConstraints.gridy = 0;
orderingInnerPanel.add(upTopButton, upTopButtonConstraints);
GridBagConstraints downBottomButtonConstraints = new GridBagConstraints();
downBottomButtonConstraints.fill = GridBagConstraints.NONE;
downBottomButtonConstraints.anchor = GridBagConstraints.LINE_START;
downBottomButtonConstraints.weighty = 1;
downBottomButtonConstraints.ipadx = 1;
downBottomButtonConstraints.gridx = 3;
downBottomButtonConstraints.gridy = 0;
orderingInnerPanel.add(downBottomButton, downBottomButtonConstraints);
return orderingPanel;
}
private JPanel createTelemetryPanel(){
JPanel telemetryPanel = new JPanel();
telemetryPanel.setLayout(new BorderLayout());
//Add title
telemetryPanel.setBorder(BorderFactory.createTitledBorder(bundle.getString("EditTelemetryTitle")));
JPanel telemetryInnerPanel = new JPanel();
telemetryPanel.add(telemetryInnerPanel, BorderLayout.WEST);
telemetryInnerPanel.setLayout(new GridBagLayout());
deleteTelemButton = new JButton(bundle.getString("RemoveTelemetryTitle"));
JRadioButton PUI = new JRadioButton();
PUI.setText("PUI");
JRadioButton baseDisplay = new JRadioButton();
baseDisplay.setText("Base Display Name");
deleteTelemButton.setName(bundle.getString("RemoveTelemetryTitle"));
deleteTelemButton.addActionListener(new ActionListener (){
@Override
public void actionPerformed(ActionEvent arg0) {
AbstractComponent t = managedExpression.getSelectedTelemetry();
if (t != null){
ExpressionsFormattingController.notifyRemoveTelem(t, managedExpression.getTelemetry());
managedExpression.getEnum().removeDelegateComponent(t);
managedExpression.fireFocusPersist();
}
}
});
GridBagConstraints deleteTelemButtonConstraints = new GridBagConstraints();
deleteTelemButtonConstraints.fill = GridBagConstraints.NONE;
deleteTelemButtonConstraints.anchor = GridBagConstraints.LINE_START;
deleteTelemButtonConstraints.weighty = .25;
deleteTelemButtonConstraints.ipadx = 1;
deleteTelemButtonConstraints.gridx = 0;
deleteTelemButtonConstraints.gridy = 0;
telemetryInnerPanel.add(deleteTelemButton, deleteTelemButtonConstraints);
return telemetryPanel;
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
515 | addExpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listenersEnabled){
ExpressionsFormattingController.notifyExpressionAdded(new Expression(), managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
516 | deleteExpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyExpressionDeleted(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
517 | addAboveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyExpressionAddedAbove(new Expression(), selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
518 | addBelowButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyExpressionAddedBelow(new Expression(), selectedExpression, managedExpression.getExpressions());
managedExpression.fireFocusPersist();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
519 | upOneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyMovedUpOne(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
520 | downOneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyMovedDownOne(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
521 | upTopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyMoveToTop(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
522 | downBottomButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expression selectedExpression = managedExpression.getSelectedExpression();
if (listenersEnabled){
ExpressionsFormattingController.notifyMoveToBottom(selectedExpression, managedExpression.getExpressions());
managedExpression.getEnum().getData().setCode(managedExpression.getExpressions().toString());
managedExpression.fireFocusPersist();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
523 | deleteTelemButton.addActionListener(new ActionListener (){
@Override
public void actionPerformed(ActionEvent arg0) {
AbstractComponent t = managedExpression.getSelectedTelemetry();
if (t != null){
ExpressionsFormattingController.notifyRemoveTelem(t, managedExpression.getTelemetry());
managedExpression.getEnum().removeDelegateComponent(t);
managedExpression.fireFocusPersist();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanel.java |
524 | public class ExpressionsFormattingControlsPanelTest {
private Robot robot;
@Mock
private ExpressionsViewManifestation mockExpManifestation;
@Mock
private EvaluatorComponent ec;
@Mock
private EvaluatorData ed;
private ArrayList<AbstractComponent> tList;
@Mock
private AbstractComponent ac;
private ExpressionsFormattingControlsPanel controlPanel;
private static final String TITLE = "Test Frame";
private static final ResourceBundle bundle = ResourceBundle.getBundle("Enumerator");
@BeforeMethod
public void setUp(){
MockitoAnnotations.initMocks(this);
robot = BasicRobot.robotWithCurrentAwtHierarchy();
tList = new ArrayList<AbstractComponent>();
tList.add(ac);
Mockito.when(mockExpManifestation.getExpressions()).thenReturn(new ExpressionList(""));
Mockito.when(mockExpManifestation.getEnum()).thenReturn(ec);
Mockito.when(ec.getData()).thenReturn(ed);
Mockito.when(ec.getComponents()).thenReturn(Collections.<AbstractComponent>emptyList());
Mockito.when(mockExpManifestation.getSelectedTelemetry()).thenReturn(ac);
Mockito.when(mockExpManifestation.getTelemetry()).thenReturn(tList);
GuiActionRunner.execute(new GuiTask(){
@Override
protected void executeInEDT() throws Throwable {
controlPanel = new ExpressionsFormattingControlsPanel(mockExpManifestation);
JFrame frame = new JFrame(TITLE);
frame.setName(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlPanel.setOpaque(true);
frame.setContentPane(controlPanel);
frame.pack();
frame.setVisible(true);
}
});
}
@AfterMethod
public void tearDown() {
robot.cleanUp();
}
@Test
public void testPersistenceIsCalledDuringActions() {
int persistentCount = 0;
FrameFixture window = WindowFinder.findFrame(TITLE).using(robot);
window.button(bundle.getString("AddExpressionTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("DeleteExpressionTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("AddAboveTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("AddBelowTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("MoveUpOneTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("MoveDownOneTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("MoveToTopTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("MoveToBottomTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("RemoveTelemetryTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
}
} | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanelTest.java |
525 | GuiActionRunner.execute(new GuiTask(){
@Override
protected void executeInEDT() throws Throwable {
controlPanel = new ExpressionsFormattingControlsPanel(mockExpManifestation);
JFrame frame = new JFrame(TITLE);
frame.setName(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlPanel.setOpaque(true);
frame.setContentPane(controlPanel);
frame.pack();
frame.setVisible(true);
}
}); | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsFormattingControlsPanelTest.java |
526 | @SuppressWarnings("serial")
public class ExpressionsViewManifestation extends View {
private static final ResourceBundle bundle = ResourceBundle.getBundle("Enumerator");
/** Expression view role name. */
public static final String VIEW_NAME = bundle.getString("ExpressionsViewRoleName");
private Expression selectedExpression;
private ExpressionList currentExpressions;
private ArrayList<AbstractComponent> telemetryElements;
private AbstractComponent selectedTelemetry;
private final EvaluatorComponent ec;
private ExpressionsFormattingControlsPanel controlPanel;
@SuppressWarnings("unused")
private ExpressionsModel expModel;
/** The telemetry model. */
public TelemetryModel telModel;
private JTable expressionsTable;
private JTable telemetryTable;
private JPanel expressionsPanel;
private JLabel resultOutput;
private JTextField testValueInput;
private Border componentBorder = null;
/**
* The expression view manifestation initialization.
* @param ac the component.
* @param vi the view info.
*/
public ExpressionsViewManifestation(AbstractComponent ac, ViewInfo vi) {
super(ac,vi);
this.ec = getManifestedComponent().getCapability(EvaluatorComponent.class);
this.selectedExpression = new Expression();
this.currentExpressions = new ExpressionList(ec.getData().getCode());
this.telemetryElements = new ArrayList<AbstractComponent>();
refreshTelemetry();
expressionsPanel = new JPanel();
expressionsPanel.getAccessibleContext().setAccessibleName("Expressions");
if (getColor("border") != null) {
componentBorder = BorderFactory.createLineBorder(getColor("border"));
}
load();
expressionsPanel.setAutoscrolls(true);
}
private Color getColor(String name) {
return UIManager.getColor(name);
}
/**
* Gets the evaluator component.
* @return the evaluator component.
*/
public EvaluatorComponent getEnum() {
return ec;
}
/**
* Gets the expression list.
* @return the expression list.
*/
public ExpressionList getExpressions(){
return currentExpressions;
}
/**
* Gets the array list of telemetry components.
* @return array list of telemetry components.
*/
public ArrayList<AbstractComponent> getTelemetry(){
return telemetryElements;
}
private void refreshTelemetry(){
telemetryElements.clear();
for (AbstractComponent component : getManifestedComponent().getComponents()){
if (component.getCapability(FeedProvider.class) != null){
telemetryElements.add(component);
}
}
}
private void load() {
buildGUI();
}
@SuppressWarnings("unused")
private boolean containsChildComponent(AbstractComponent parentComponent, String childComponentId) {
for (AbstractComponent childComponent : parentComponent.getComponents()) {
if (childComponentId.equals(childComponent.getComponentId())){
return true;
}
}
return false;
}
private void buildGUI() {
//show associated telemetry element, table of expressions, test value
setLayout(new GridBagLayout());
//Input area for test value at top of view
testValueInput = new JTextField();
testValueInput.setEditable(true);
JLabel testValue = new JLabel("Test Value: ");
JLabel result = new JLabel("Result: ");
resultOutput = new JLabel();
testValueInput.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
String t = testValueInput.getText();
t = evaluate(t);
resultOutput.setText(t);
}
});
testValueInput.getAccessibleContext().setAccessibleName(testValue.getText());
//Add table of expressions
expressionsTable = new JTable(expModel = new ExpressionsModel());
expressionsTable.setAutoCreateColumnsFromModel(true);
expressionsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
expressionsTable.setRowSelectionAllowed(true);
setOpColumn(expressionsTable, expressionsTable.getColumnModel().getColumn(0));
JScrollPane expressionsTableScrollPane = new JScrollPane(expressionsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
GridBagConstraints eTableConstraints = getConstraints(0,2);
eTableConstraints.gridwidth = 3;
eTableConstraints.fill = GridBagConstraints.HORIZONTAL;
eTableConstraints.gridheight = 7;
eTableConstraints.insets = new Insets(1,9,9,9);
eTableConstraints.weightx = 1;
eTableConstraints.weighty = .7;
add(expressionsTableScrollPane, eTableConstraints);
//Add table of telemetry elements
telemetryTable = new JTable(telModel = new TelemetryModel());
telemetryTable.setAutoCreateColumnsFromModel(true);
telemetryTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
telemetryTable.setRowSelectionAllowed(true);
telemetryTable.setAutoCreateRowSorter(true);
JScrollPane telemetryTableScrollPane = new JScrollPane(telemetryTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
if (componentBorder != null) {
expressionsTableScrollPane.setBorder(componentBorder);
telemetryTableScrollPane.setBorder(componentBorder);
testValueInput.setBorder(componentBorder);
}
GridBagConstraints tTableConstraints = getConstraints(0,13);
tTableConstraints.gridwidth = 3;
tTableConstraints.gridheight = 1;
tTableConstraints.insets = new Insets(1,9,9,9);
tTableConstraints.weightx = 1;
tTableConstraints.weighty = .3;
tTableConstraints.anchor = GridBagConstraints.WEST;
tTableConstraints.fill = GridBagConstraints.HORIZONTAL;
add(telemetryTableScrollPane, tTableConstraints);
//Add test value + results
GridBagConstraints tValueConstraints = getConstraints(0,0);
tValueConstraints.insets = new Insets(9,9,2,1);
add(testValue, tValueConstraints);
GridBagConstraints tValueInputConstraints = getConstraints(1,0);
tValueInputConstraints.insets = new Insets(9,1,2,9);
add(testValueInput, tValueInputConstraints);
GridBagConstraints rConstraints = getConstraints(0,1);
rConstraints.insets = new Insets(3,9,5,1);
add(result, rConstraints);
GridBagConstraints rOutputConstraints = getConstraints(1,1);
rOutputConstraints.insets = new Insets (3,1,5,9);
add(resultOutput, rOutputConstraints);
}
/**
* Combo box for operator choices in a table column.
* @param table the JTable.
* @param opCol the table column.
*/
public void setOpColumn(JTable table, TableColumn opCol) {
JComboBox selector = new JComboBox();
selector.addItem("=");
selector.addItem("<");
selector.addItem(">");
selector.addItem(EnumEvaluator.NOT_EQUALS);
opCol.setCellEditor(new DefaultCellEditor(selector));
}
private GridBagConstraints getConstraints(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = x == 0 ? 0 : 1;
gbc.weighty = 0;
gbc.insets = new Insets(0,9,4,9);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTHWEST;
return gbc;
}
/**
* Evaluates the result.
* @param value the string value.
* @return the evaluated result.
*/
public String evaluate(String value){
EnumEvaluator e = new EnumEvaluator();
e.compile(ec.getData().getCode());
return e.evaluate(value);
}
/**
* Expressions table model.
*/
@SuppressWarnings("unchecked")
class ExpressionsModel extends AbstractTableModel {
private ExpressionList eList = currentExpressions;
private List<String> ops = new ArrayList<String>();
private List<String> values = new ArrayList<String>();
private List<String> displays = new ArrayList<String>();
private List<List<String>> lists = Arrays.asList(ops, values, displays);
private final List<String> columnNames = new ArrayList<String>();
/**
* Initializes the expression model.
*/
ExpressionsModel(){
columnNames.add(bundle.getString("OpLabel"));
columnNames.add(bundle.getString("ValueLabel"));
columnNames.add(bundle.getString("DisplayLabel"));
loadExpressions();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return eList.size();
}
@Override
public boolean isCellEditable(int row, int col) {
return true;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnIndex == 1 ? Double.class : String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex){
List<String> list = getListForColumn(columnIndex);
String value = list.get(rowIndex);
return columnIndex == 1 ? Double.valueOf(value) : value;
}
private List<String> getListForColumn(int col){
return lists.get(col);
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col==0){
eList.getExp(row).setOperator(value.toString());
}
if (col==1 && value != null){
eList.getExp(row).setVal(Double.valueOf(value.toString()));
}
if (col==2){
eList.getExp(row).setDisplay(value.toString());
}
ec.getData().setCode(eList.toString());
fireTableCellUpdated(row, col);
fireFocusPersist();
}
private void loadExpressions(){
Expression e;
for (int i = 0; i < eList.size(); i++){
e = eList.getExp(i);
ops.add(e.getOperator());
values.add(Double.toString(e.getVal()));
displays.add(e.getDisplay());
}
}
/**
* Clears the model.
*/
public void clearModel() {
ops.clear();
values.clear();
displays.clear();
loadExpressions();
fireTableDataChanged();
}
}
/**
* Telemetry model.
*/
@SuppressWarnings("unchecked")
class TelemetryModel extends AbstractTableModel{
private List<String> pui = new ArrayList<String>();
private List<String> baseDisplay = new ArrayList<String>();
private List<List<String>> lists = Arrays.asList(pui, baseDisplay);
private final List<String> columnNames = new ArrayList<String>();
/**
* Initializes the telemetry model.
*/
TelemetryModel(){
columnNames.add(bundle.getString("PuiLabel"));
columnNames.add(bundle.getString("BaseDisplayLabel"));
loadTelemetry();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return telemetryElements.size();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex){
List<String> list = getListForColumn(columnIndex);
return list.get(rowIndex);
}
private List<String> getListForColumn(int col){
return lists.get(col);
}
/**
* Loads the telemetry.
*/
protected void loadTelemetry(){
refreshTelemetry();
for (AbstractComponent ac : telemetryElements){
pui.add(ac.getExternalKey());
baseDisplay.add(ac.getDisplayName());
}
}
/**
* Clears the telemetry model.
*/
public void clearModel() {
pui.clear();
baseDisplay.clear();
loadTelemetry();
fireTableDataChanged();
}
}
@Override
protected JComponent initializeControlManifestation() {
//Set canvas control
this.controlPanel = new ExpressionsFormattingControlsPanel(this);
Dimension d = controlPanel.getMinimumSize();
d.setSize(0,0);
controlPanel.setMinimumSize(d);
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
pane.setOneTouchExpandable(true);
pane.setBorder(BorderFactory.createEmptyBorder());
JScrollPane controlScrollPane = new JScrollPane(controlPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
return controlScrollPane;
}
/**
* Gets the selected expression.
* @return the expression.
*/
public Expression getSelectedExpression(){
int row = expressionsTable.getSelectedRowCount();
if (row == 1){
selectedExpression = currentExpressions.getExp(expressionsTable.getSelectedRow());
}
else {
selectedExpression = null;
}
return selectedExpression;
}
/**
* Gets the selected telemetry.
* @return the component.
*/
public AbstractComponent getSelectedTelemetry(){
int row = telemetryTable.getSelectedRowCount();
if (row == 1){
selectedTelemetry = telemetryElements.get(telemetryTable.getSelectedRow());
}
else {
selectedTelemetry = null;
}
return selectedTelemetry;
}
/**
* Saves the manifested component.
*/
public void fireFocusPersist(){
if (!isLocked()) {
getManifestedComponent().save();
updateMonitoredGUI();
}
}
/**
* Fires the selection property changes.
*/
public void fireManifestationChanged() {
firePropertyChange(SelectionProvider.SELECTION_CHANGED_PROP, null, getSelectedExpression());
}
@Override
public void updateMonitoredGUI(){
((ExpressionsModel)expressionsTable.getModel()).clearModel();
((TelemetryModel)telemetryTable.getModel()).clearModel();
}
@Override
public void updateMonitoredGUI(AddChildEvent event) {
((TelemetryModel)telemetryTable.getModel()).clearModel();
}
@Override
public void updateMonitoredGUI(RemoveChildEvent event) {
((TelemetryModel)telemetryTable.getModel()).clearModel();
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsViewManifestation.java |
527 | testValueInput.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
String t = testValueInput.getText();
t = evaluate(t);
resultOutput.setText(t);
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsViewManifestation.java |
528 | @SuppressWarnings("unchecked")
class ExpressionsModel extends AbstractTableModel {
private ExpressionList eList = currentExpressions;
private List<String> ops = new ArrayList<String>();
private List<String> values = new ArrayList<String>();
private List<String> displays = new ArrayList<String>();
private List<List<String>> lists = Arrays.asList(ops, values, displays);
private final List<String> columnNames = new ArrayList<String>();
/**
* Initializes the expression model.
*/
ExpressionsModel(){
columnNames.add(bundle.getString("OpLabel"));
columnNames.add(bundle.getString("ValueLabel"));
columnNames.add(bundle.getString("DisplayLabel"));
loadExpressions();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return eList.size();
}
@Override
public boolean isCellEditable(int row, int col) {
return true;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnIndex == 1 ? Double.class : String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex){
List<String> list = getListForColumn(columnIndex);
String value = list.get(rowIndex);
return columnIndex == 1 ? Double.valueOf(value) : value;
}
private List<String> getListForColumn(int col){
return lists.get(col);
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col==0){
eList.getExp(row).setOperator(value.toString());
}
if (col==1 && value != null){
eList.getExp(row).setVal(Double.valueOf(value.toString()));
}
if (col==2){
eList.getExp(row).setDisplay(value.toString());
}
ec.getData().setCode(eList.toString());
fireTableCellUpdated(row, col);
fireFocusPersist();
}
private void loadExpressions(){
Expression e;
for (int i = 0; i < eList.size(); i++){
e = eList.getExp(i);
ops.add(e.getOperator());
values.add(Double.toString(e.getVal()));
displays.add(e.getDisplay());
}
}
/**
* Clears the model.
*/
public void clearModel() {
ops.clear();
values.clear();
displays.clear();
loadExpressions();
fireTableDataChanged();
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsViewManifestation.java |
529 | @SuppressWarnings("unchecked")
class TelemetryModel extends AbstractTableModel{
private List<String> pui = new ArrayList<String>();
private List<String> baseDisplay = new ArrayList<String>();
private List<List<String>> lists = Arrays.asList(pui, baseDisplay);
private final List<String> columnNames = new ArrayList<String>();
/**
* Initializes the telemetry model.
*/
TelemetryModel(){
columnNames.add(bundle.getString("PuiLabel"));
columnNames.add(bundle.getString("BaseDisplayLabel"));
loadTelemetry();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return telemetryElements.size();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex){
List<String> list = getListForColumn(columnIndex);
return list.get(rowIndex);
}
private List<String> getListForColumn(int col){
return lists.get(col);
}
/**
* Loads the telemetry.
*/
protected void loadTelemetry(){
refreshTelemetry();
for (AbstractComponent ac : telemetryElements){
pui.add(ac.getExternalKey());
baseDisplay.add(ac.getDisplayName());
}
}
/**
* Clears the telemetry model.
*/
public void clearModel() {
pui.clear();
baseDisplay.clear();
loadTelemetry();
fireTableDataChanged();
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_ExpressionsViewManifestation.java |
530 | public class MultiExpressionsControlPanelTest {
private Robot robot;
@Mock
private MultiViewManifestation mockExpManifestation;
@Mock
private MultiComponent mc;
@Mock
private MultiData multiData;
private ArrayList<AbstractComponent> tList;
@Mock
private AbstractComponent ac;
@Mock
private MultiRuleExpressionList ruleList;
@Mock
private MultiRuleExpression expression;
private MultiExpressionsFormattingControlsPanel controlPanel;
private static final String TITLE = "Test Frame";
private static final ResourceBundle bundle = ResourceBundle.getBundle("MultiComponent");
@BeforeMethod
public void setUp(){
MockitoAnnotations.initMocks(this);
robot = BasicRobot.robotWithCurrentAwtHierarchy();
tList = new ArrayList<AbstractComponent>();
tList.add(ac);
FeedProvider mockfp = Mockito.mock(FeedProvider.class);
Mockito.when(mockExpManifestation.getExpressions()).thenReturn(ruleList);
Mockito.when(ruleList.size()).thenReturn(2);
Mockito.when(mockExpManifestation.getMulti()).thenReturn(mc);
Mockito.when(mc.getData()).thenReturn(multiData);
Mockito.when(ac.getExternalKey()).thenReturn("isp:PARAMETER1");
Mockito.when(ac.getCapability(FeedProvider.class)).thenReturn(mockfp);
Mockito.when(mockfp.getSubscriptionId()).thenReturn("isp:PARAMETER1");
Mockito.when(multiData.isPassThrough()).thenReturn(false);
Mockito.when(mc.getComponents()).thenReturn(Collections.<AbstractComponent>emptyList());
Mockito.when(mockExpManifestation.getSelectedTelemetry()).thenReturn(ac);
Mockito.when(mockExpManifestation.getTelemetry()).thenReturn(tList);
GuiActionRunner.execute(new GuiTask(){
@Override
protected void executeInEDT() throws Throwable {
controlPanel = new MultiExpressionsFormattingControlsPanel(mockExpManifestation);
JFrame frame = new JFrame(TITLE);
frame.setPreferredSize(new Dimension(950,600));
frame.setName(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlPanel.setOpaque(true);
frame.setContentPane(controlPanel);
frame.pack();
frame.setVisible(true);
}
});
}
@AfterMethod
public void tearDown() {
robot.cleanUp();
}
@Test
public void testPersistenceIsCalledDuringActions() {
int persistentCount = 0;
FrameFixture window = WindowFinder.findFrame(TITLE).using(robot);
window.button(bundle.getString("AddExpressionTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.textBox(bundle.getString("ValueControlName")).setText("1.0");
window.textBox(bundle.getString("DisplayControlName")).setText("test display");
Mockito.when(mockExpManifestation.getSelectedExpression()).thenReturn(expression);
Mockito.when(expression.getPUIs()).thenReturn("isp:PARAMETER1");
window.button(bundle.getString("ApplyTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.textBox(bundle.getString("ValueControlName")).setText("test value2");
window.textBox(bundle.getString("DisplayControlName")).setText("test display2");
window.button(bundle.getString("ApplyTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("AddExpressionTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.textBox(bundle.getString("ValueControlName")).setText("1.0");
window.textBox(bundle.getString("DisplayControlName")).setText("test display");
Mockito.when(mockExpManifestation.getSelectedExpression()).thenReturn(expression);
Mockito.when(expression.getPUIs()).thenReturn("isp:PARAMETER1");
window.button(bundle.getString("ApplyTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("MoveUpOneTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("MoveDownOneTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.button(bundle.getString("DeleteExpressionTitle")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
window.checkBox(bundle.getString("PassThroughControl")).click();
Mockito.verify(mockExpManifestation, Mockito.times(++persistentCount)).fireFocusPersist();
}
} | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsControlPanelTest.java |
531 | GuiActionRunner.execute(new GuiTask(){
@Override
protected void executeInEDT() throws Throwable {
controlPanel = new MultiExpressionsFormattingControlsPanel(mockExpManifestation);
JFrame frame = new JFrame(TITLE);
frame.setPreferredSize(new Dimension(950,600));
frame.setName(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlPanel.setOpaque(true);
frame.setContentPane(controlPanel);
frame.pack();
frame.setVisible(true);
}
}); | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsControlPanelTest.java |
532 | public class MultiExpressionsController {
private MultiViewManifestation multiViewManifestation;
/** Create a controller for rule expressions.
* @param manifestation the manifestation.
*/
public MultiExpressionsController(MultiViewManifestation manifestation) {
this.multiViewManifestation = manifestation;
}
/**
* Notifies that a new expression has been created.
* @param newExp the new expression to add.
* @param expList the expression list to add.
*/
public void notifyExpressionAdded(MultiRuleExpression newExp, MultiRuleExpressionList expList){
if (expList != null) {
expList.addExp(newExp);
multiViewManifestation.refreshRuleExpressions();
multiViewManifestation.setSelectedExpression(newExp);
}
}
/**
* Notifies the an existing expression has been deleted.
* @param selectedExp the selected expression to delete.
* @param expList the expression list to delete.
*/
public void notifyExpressionDeleted(MultiRuleExpression selectedExp, MultiRuleExpressionList expList){
if (selectedExp != null && expList != null){
expList.deleteExp(selectedExp);
multiViewManifestation.refreshRuleExpressions();
}
}
/**
* Notifies that an existing expression has been added on top.
* @param newExp the new expression to add above.
* @param selectedExp the selected expression to add from.
* @param expList the expression list to add to.
*/
public void notifyExpressionAddedAbove(MultiRuleExpression newExp, MultiRuleExpression selectedExp, MultiRuleExpressionList expList){
if (newExp != null && selectedExp != null && expList != null) {
int index = expList.indexOf(selectedExp);
expList.addExp(index, newExp);
}
}
/**
* Notifies than an existing expression has been added below.
* @param newExp the new expression to add below.
* @param selectedExp the selected expression to add to.
* @param expList the expression list to add to.
*/
public void notifyExpressionAddedBelow(MultiRuleExpression newExp, MultiRuleExpression selectedExp, MultiRuleExpressionList expList){
if (newExp != null && selectedExp != null && expList != null) {
int index = expList.indexOf(selectedExp);
expList.addExp(index+1, newExp);
}
}
/**
* Notifies to move expression up one.
* @param exp the expression to move up one.
* @param expList the expression list.
*/
public void notifyMovedUpOne(MultiRuleExpression exp, MultiRuleExpressionList expList){
if (exp != null && expList != null){
int index = expList.indexOf(exp);
if (index > 0) {
expList.move(index-1, exp);
multiViewManifestation.refreshRuleExpressions();
}
}
}
/**
* Notifies to move expression down one.
* @param exp the expression to move down one.
* @param expList the expression list.
*/
public void notifyMovedDownOne(MultiRuleExpression exp, MultiRuleExpressionList expList){
if (exp != null && expList != null){
int index = expList.indexOf(exp);
if (index < expList.size()-1) {
expList.move(index+1, exp);
multiViewManifestation.refreshRuleExpressions();
}
}
}
/**
* Notifies to update a multi rule expression .
* @param index the index of the rule expression to update.
* @param expList the list of expressions.
* @param exp the new rule expression
*/
public void notifyRuleUpdated(int index, MultiRuleExpressionList expList,
MultiRuleExpression exp){
expList.updateExp(index, exp);
multiViewManifestation.refreshRuleExpressions();
multiViewManifestation.setSelectedExpression(exp);
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsController.java |
533 | public class MultiExpressionsFormattingControllerTest {
private MultiRuleExpression e1, e2, e3;
private MultiRuleExpressionList eList;
private MultiExpressionsController controller;
private ArrayList<AbstractComponent> tList;
@Mock
private AbstractComponent t;
@Mock private MultiViewManifestation view;
@BeforeMethod
public void setup(){
MockitoAnnotations.initMocks(this);
eList = new MultiRuleExpressionList("");
e1 = new MultiRuleExpression(SetLogic.ALL_PARAMETERS, new String[] {"PUI1","PUI2"},
"PUI1","=", "abc", "display", "rule1");
e2 = new MultiRuleExpression(SetLogic.ALL_PARAMETERS, new String[] {"PUI1","PUI2"},
"PUI1","=", "abc", "display", "rule2");
e3 = new MultiRuleExpression(SetLogic.ALL_PARAMETERS, new String[] {"PUI1","PUI2"},
"PUI1","=", "abc", "display", "rule3");
tList = new ArrayList<AbstractComponent>();
controller = new MultiExpressionsController(view);
}
@AfterMethod
public void tearDown() {
this.eList = new MultiRuleExpressionList("");
}
@Test
public void notifyExpressionAddedTest(){
controller.notifyExpressionAdded(e1, eList);
Assert.assertEquals(eList.size(), 1);
Assert.assertEquals(eList.getExp(0), e1);
}
@Test
public void notifyExpressionDeletedTest(){
eList.addExp(e1);
eList.addExp(e2);
controller.notifyExpressionDeleted(e2, eList);
Assert.assertEquals(eList.size(), 1);
Assert.assertEquals(eList.getExp(0), e1);
}
@Test
public void notifyMovedUpOneTest(){
eList.addExp(e1);
eList.addExp(e2);
controller.notifyMovedUpOne(e2, eList);
Assert.assertEquals(eList.getExp(0), e2);
}
@Test
public void notifyMovedDownOneTest(){
eList.addExp(e1);
eList.addExp(e2);
controller.notifyMovedDownOne(e1, eList);
Assert.assertEquals(eList.getExp(0), e2);
}
} | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControllerTest.java |
534 | @SuppressWarnings("serial")
public class MultiExpressionsFormattingControlsPanel extends JPanel {
private static final ResourceBundle bundle = ResourceBundle.getBundle("MultiComponent");
private static final Map<String,SetLogic> setLogicStrings = new HashMap<String,SetLogic>();
private static final String[] setLogicFields = {"Single parameter",
"More than 1 parameter", "All parameters"};
private static final String[] opStrings = { "\u2260","<",">","=" };
private JPanel controlPanel;
private JPanel ruleTablePanel;
private JPanel bottomPanel;
//Creation Panel
private JButton addExpButton = null;
private JButton deleteExpButton = null;
private JButton applyButton = null;
//Expression Order Editing Panel
private JButton upOneButton = null;
private JButton downOneButton = null;
private JComboBox ifComboBox = null;
private JComboBox parameterComboBox = null;
private JComboBox opComboBox = null;
private JTextField indeterminateTextField = null;
private JTextField ruleNameTextField = null;
private JTextField ruleResultTextField = null;
private JFormattedTextField valueTextField = null;
private JTextField displayTextField = null;
private JCheckBox passThroughCheckBox;
private boolean listenersEnabled = true;
private boolean applyButtonListenersEnabled = true;
private final MultiViewManifestation multiViewManifestation;
private MultiExpressionsController controller;
static {
setLogicStrings.put("Single parameter", SetLogic.SINGLE_PARAMETER);
setLogicStrings.put("More than 1 parameter", SetLogic.MORE_THAN_ONE_PARAMETER);
setLogicStrings.put("All parameters",SetLogic.ALL_PARAMETERS);
}
/**
* Initialize the expressions format control panel.
* @param multiViewManifestation the view manifestation.
*/
MultiExpressionsFormattingControlsPanel (MultiViewManifestation multiView) {
this.multiViewManifestation = multiView;
controlPanel = createExpressionsFormattingControlsPanel();
loadRuleButtonSettings();
controller = new MultiExpressionsController(multiView);
this.add(controlPanel);
if (multiViewManifestation.getExpressions().size() == 0) {
ruleTablePanel.setVisible(false);
bottomPanel.setVisible(false);
}
}
/**
* Load the states of the controls based on current rule set.
*/
public void loadRuleButtonSettings() {
if (multiViewManifestation.getTelemetry().size() == 0 ||
multiViewManifestation.getMulti().getData().isPassThrough()) {
addExpButton.setEnabled(false);
deleteExpButton.setEnabled(false);
upOneButton.setEnabled(false);
downOneButton.setEnabled(false);
} else {
addExpButton.setEnabled(true);
if (multiViewManifestation.getExpressions().size() == 0) {
deleteExpButton.setEnabled(false);
} else {
if (multiViewManifestation.getSelectedExpression() != null) {
deleteExpButton.setEnabled(true);
} else {
deleteExpButton.setEnabled(false);
}
}
if (multiViewManifestation.getExpressions().size() >= 2 &&
multiViewManifestation.getSelectedExpression() != null) {
upOneButton.setEnabled(true);
downOneButton.setEnabled(true);
} else {
upOneButton.setEnabled(false);
downOneButton.setEnabled(false);
}
}
}
private JPanel createExpressionsFormattingControlsPanel() {
JPanel controlPanel = new JPanel (new GridBagLayout());
JPanel creationPanel = createCreationPanel(true);
JPanel indeterminatePanel = createIndeterminatePanel();
//Creation Panel
GridBagConstraints creationPanelConstraints = new GridBagConstraints();
creationPanelConstraints.fill = GridBagConstraints.NONE;
creationPanelConstraints.anchor = GridBagConstraints.NORTHWEST;
creationPanelConstraints.weighty = 0;
creationPanelConstraints.weightx = 1;
creationPanelConstraints.insets = new Insets(3,7,3,7);
creationPanelConstraints.gridx = 0;
creationPanelConstraints.gridy = 0;
controlPanel.add(creationPanel, creationPanelConstraints);
//Indeterminate Panel
GridBagConstraints indeterminatePanelConstraints = new GridBagConstraints();
indeterminatePanelConstraints.fill = GridBagConstraints.NONE;
indeterminatePanelConstraints.anchor = GridBagConstraints.NORTHWEST;
indeterminatePanelConstraints.weighty = 1;
indeterminatePanelConstraints.weightx = 1;
indeterminatePanelConstraints.insets = new Insets(3,7,3,7);
indeterminatePanelConstraints.gridx = 0;
indeterminatePanelConstraints.gridy = 2;
controlPanel.add(indeterminatePanel, indeterminatePanelConstraints);
controlPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
this.setLayout(new GridLayout(1,0));
return controlPanel;
}
private JPanel createRuleTablePanel() {
ruleTablePanel = new JPanel();
ruleTablePanel.setLayout(new GridBagLayout());
JPanel ruleTableInnerPanel = new JPanel(new GridBagLayout());
ruleTableInnerPanel.setBorder(BorderFactory.createEmptyBorder(5,2,2,2));
GridBagConstraints ruleListInnerPanelConstraints = new GridBagConstraints();
ruleListInnerPanelConstraints.fill = GridBagConstraints.NONE;
ruleListInnerPanelConstraints.anchor = GridBagConstraints.LINE_START;
ruleListInnerPanelConstraints.weighty = 1;
ruleListInnerPanelConstraints.weightx = 0;
ruleListInnerPanelConstraints.ipadx = 1;
ruleListInnerPanelConstraints.gridx = 0;
ruleListInnerPanelConstraints.gridy = 0;
ruleTableInnerPanel.add(new JLabel(bundle.getString("RuleNameLabel")), ruleListInnerPanelConstraints);
GridBagConstraints ruleListInnerPanelConstraints3 = new GridBagConstraints();
ruleListInnerPanelConstraints3.fill = GridBagConstraints.NONE;
ruleListInnerPanelConstraints3.anchor = GridBagConstraints.LINE_START;
ruleListInnerPanelConstraints3.weighty = 1;
ruleListInnerPanelConstraints3.weightx = 0;
ruleListInnerPanelConstraints3.ipadx = 1;
ruleListInnerPanelConstraints3.gridx = 1;
ruleListInnerPanelConstraints3.gridy = 0;
ruleNameTextField = new JTextField();
ruleNameTextField.setPreferredSize(new Dimension(150,20));
ruleNameTextField.setEditable(true);
ruleNameTextField.getDocument().addDocumentListener(new ApplyButtonListener());
ruleTableInnerPanel.add(ruleNameTextField, ruleListInnerPanelConstraints3);
GridBagConstraints ruleListInnerPanelConstraints4 = new GridBagConstraints();
ruleListInnerPanelConstraints4.fill = GridBagConstraints.NONE;
ruleListInnerPanelConstraints4.anchor = GridBagConstraints.LINE_START;
ruleListInnerPanelConstraints4.weighty = 1;
ruleListInnerPanelConstraints4.weightx = 0;
ruleListInnerPanelConstraints4.ipadx = 1;
ruleListInnerPanelConstraints4.gridx = 0;
ruleListInnerPanelConstraints4.gridy = 0;
ruleTablePanel.add(ruleTableInnerPanel, ruleListInnerPanelConstraints4);
final int borderWidth = 2;
JPanel tablePanel = new JPanel(new GridLayout(0, 5));
tablePanel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
JPanel ifPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
ifPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
ifPanel.add(new JLabel(bundle.getString("IfLabel")));
JPanel parametersPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
parametersPanel.setBorder(BorderFactory.createMatteBorder(borderWidth,
0,
borderWidth,
borderWidth,
Color.BLACK));
parametersPanel.add(new JLabel(bundle.getString("ParameterLabel")));
JPanel opPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
opPanel.setBorder(BorderFactory.createMatteBorder(borderWidth,
0,
borderWidth,
borderWidth,
Color.BLACK));
opPanel.add(new JLabel(bundle.getString("OpLabel")));
JPanel valuePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
valuePanel.setBorder(BorderFactory.createMatteBorder(borderWidth,
0,
borderWidth,
borderWidth,
Color.BLACK));
valuePanel.add(new JLabel(bundle.getString("ValueLabel")));
JPanel displayPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
displayPanel.setBorder(BorderFactory.createMatteBorder(borderWidth,
0,
borderWidth,
borderWidth,
Color.BLACK));
displayPanel.add(new JLabel(bundle.getString("DisplayLabel")));
tablePanel.add(ifPanel, 0);
tablePanel.add(parametersPanel, 1);
tablePanel.add(opPanel, 2);
tablePanel.add(valuePanel, 3);
tablePanel.add(displayPanel, 4);
// Add rule components
JPanel ifChoicePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
ifChoicePanel.setBorder(BorderFactory.createMatteBorder(0,
borderWidth,
borderWidth,
borderWidth,
Color.BLACK));
ifComboBox = new JComboBox(setLogicFields);
ifComboBox.addActionListener(new ApplyActionListener());
ifChoicePanel.add(ifComboBox);
tablePanel.add(ifChoicePanel);
JPanel paramChoicePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
paramChoicePanel.setBorder(BorderFactory.createMatteBorder(0,
0,
borderWidth,
borderWidth,
Color.BLACK));
parameterComboBox = new JComboBox(getTelemetryIDs());
parameterComboBox.addActionListener(new ApplyActionListener());
paramChoicePanel.add(parameterComboBox);
tablePanel.add(paramChoicePanel);
JPanel opChoicePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
opChoicePanel.setBorder(BorderFactory.createMatteBorder(0,
0,
borderWidth,
borderWidth,
Color.BLACK));
opComboBox = new JComboBox(opStrings);
opComboBox.addActionListener(new ApplyActionListener());
opChoicePanel.add(opComboBox);
tablePanel.add(opChoicePanel);
JPanel valueChoicePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
valueChoicePanel.setBorder(BorderFactory.createMatteBorder(0,
0,
borderWidth,
borderWidth,
Color.BLACK));
NumberFormat generalNumberFormat = NumberFormat.getInstance();
valueTextField = new JFormattedTextField(generalNumberFormat);
valueTextField.setEditable(true);
valueTextField.setName(bundle.getString("ValueControlName"));
valueTextField.setPreferredSize(new Dimension(100,20));
valueTextField.getDocument().addDocumentListener(new ApplyButtonListener());
valueChoicePanel.add(valueTextField);
tablePanel.add(valueChoicePanel);
JPanel displayChoicePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
displayChoicePanel.setBorder(BorderFactory.createMatteBorder(0,
0,
borderWidth,
borderWidth,
Color.BLACK));
displayTextField = new JTextField();
displayTextField.setEditable(true);
displayTextField.setName(bundle.getString("DisplayControlName"));
displayTextField.setPreferredSize(new Dimension(100,20));
displayTextField.getDocument().addDocumentListener(new ApplyButtonListener());
displayChoicePanel.add(displayTextField);
tablePanel.add(displayChoicePanel);
GridBagConstraints ruleListInnerPanelConstraints2 = new GridBagConstraints();
ruleListInnerPanelConstraints2.fill = GridBagConstraints.NONE;
ruleListInnerPanelConstraints2.anchor = GridBagConstraints.LINE_START;
ruleListInnerPanelConstraints2.weighty = 1;
ruleListInnerPanelConstraints2.weightx = 0;
ruleListInnerPanelConstraints2.ipadx = 1;
ruleListInnerPanelConstraints2.gridx = 0;
ruleListInnerPanelConstraints2.gridy = 1;
ruleTablePanel.add(tablePanel, ruleListInnerPanelConstraints2);
return ruleTablePanel;
}
private class ApplyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (displayTextField.getText().isEmpty() || valueTextField.getText().isEmpty()) {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(false);
}
applyButton.setToolTipText("Rule value or display fields do not contain valid values");
ruleNameTextField.setToolTipText(ruleNameTextField.getText());
} else {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(true);
}
applyButton.setToolTipText("Apply changes to this rule");
}
displayTextField.setToolTipText(displayTextField.getText());
valueTextField.setToolTipText(valueTextField.getText());
}
}
private class ApplyButtonListener implements DocumentListener {
public void insertUpdate(DocumentEvent event) {
if (displayTextField.getText().isEmpty() || valueTextField.getText().isEmpty()) {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(false);
}
applyButton.setToolTipText("Rule value or display fields do not contain valid values");
ruleNameTextField.setToolTipText(ruleNameTextField.getText());
} else {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(true);
}
applyButton.setToolTipText("Apply changes to this rule");
}
displayTextField.setToolTipText(displayTextField.getText());
valueTextField.setToolTipText(valueTextField.getText());
}
public void removeUpdate(DocumentEvent event) {
if (displayTextField.getText().isEmpty() || valueTextField.getText().isEmpty()) {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(false);
}
applyButton.setToolTipText("Rule value or display fields do not contain valid values");
} else {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(true);
}
applyButton.setToolTipText("Apply changes to this rule");
}
displayTextField.setToolTipText(displayTextField.getText());
valueTextField.setToolTipText(valueTextField.getText());
}
@Override
public void changedUpdate(DocumentEvent e) {
}
}
private String[] addDataFeedPrefixes(String[] puis) {
if (puis == null) return null;
String[] returnStrings = new String[puis.length];
for (int i=0 ; i < puis.length ; i++) {
if (!puis[i].contains(":") && bundle.getString("DataFeedPrefix").length() > 0){
returnStrings[i] = bundle.getString("DataFeedPrefix") + puis[i];
} else {
returnStrings[i] = puis[i];
}
}
return returnStrings;
}
private String[] getTelemetryIDs() {
List<String> ids = new ArrayList<String>();
for (AbstractComponent ac : multiViewManifestation.getTelemetry()) {
ids.add(ac.getCapability(FeedProvider.class).getSubscriptionId());
}
return ids.toArray(new String[0]);
}
/**
* Set the pass through function according to the component state.
*/
public void updatePassThroughControl() {
if (multiViewManifestation.getTelemetry().size() != 1) {
if (passThroughCheckBox.isSelected()) {
passThroughCheckBox.setSelected(false);
multiViewManifestation.getMulti().getData().setPassThrough(false);
}
passThroughCheckBox.setEnabled(false);
} else {
passThroughCheckBox.setEnabled(true);
}
}
private JPanel createCreationPanel(boolean includeRuleTable) {
JPanel creationPanel = new JPanel();
creationPanel.setLayout(new GridBagLayout());
//Add title
creationPanel.setBorder(BorderFactory.createTitledBorder(bundle.getString("CreateDeleteTitle")));
JPanel creationInnerPanel = new JPanel();
GridBagConstraints innerPanelConstraints = new GridBagConstraints();
innerPanelConstraints.fill = GridBagConstraints.NONE;
innerPanelConstraints.anchor = GridBagConstraints.LINE_START;
innerPanelConstraints.weighty = 1;
innerPanelConstraints.weightx = 0;
innerPanelConstraints.ipadx = 1;
innerPanelConstraints.gridx = 0;
innerPanelConstraints.gridy = 1;
creationPanel.add(creationInnerPanel, innerPanelConstraints);
JPanel checkBoxPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
passThroughCheckBox = new JCheckBox();
passThroughCheckBox.setName(bundle.getString("PassThroughControl"));
if (multiViewManifestation.getTelemetry().size() != 1) {
passThroughCheckBox.setEnabled(false);
}
if (multiViewManifestation.getMulti().getData().isPassThrough()) {
passThroughCheckBox.setSelected(true);
}
passThroughCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AbstractButton abstractButton = (AbstractButton) e.getSource();
if (abstractButton.getModel().isSelected()) {
multiViewManifestation.getMulti().getData().setPassThrough(true);
multiViewManifestation.getMulti().getData().setPassThroughParameterId(multiViewManifestation.getTelemetry().get(0).getCapability(FeedProvider.class).getSubscriptionId());
addExpButton.setEnabled(false);
deleteExpButton.setEnabled(false);
upOneButton.setEnabled(false);
downOneButton.setEnabled(false);
} else {
multiViewManifestation.getMulti().getData().setPassThrough(false);
multiViewManifestation.getMulti().getData().setPassThroughParameterId(null);
addExpButton.setEnabled(true);
deleteExpButton.setEnabled(true);
upOneButton.setEnabled(true);
downOneButton.setEnabled(true);
}
multiViewManifestation.fireFocusPersist();
}
});
checkBoxPanel.add(passThroughCheckBox);
checkBoxPanel.add(new JLabel(bundle.getString("PassThroughLabel")));
creationInnerPanel.setLayout(new GridBagLayout());
//Creation controls
addExpButton = new JButton(bundle.getString("AddExpressionTitle"));
deleteExpButton = new JButton(bundle.getString("DeleteExpressionTitle"));
upOneButton = new JButton(bundle.getString("MoveUpOneTitle"));
downOneButton = new JButton(bundle.getString("MoveDownOneTitle"));
applyButton = new JButton(bundle.getString("ApplyTitle"));
addExpButton.setName(bundle.getString("AddExpressionTitle"));
deleteExpButton.setName(bundle.getString("DeleteExpressionTitle"));
upOneButton.setName(bundle.getString("MoveUpOneTitle"));
downOneButton.setName(bundle.getString("MoveDownOneTitle"));
applyButton.setName(bundle.getString("ApplyTitle"));
addExpButton.setToolTipText(bundle.getString("AddExpressionToolTip"));
deleteExpButton.setToolTipText(bundle.getString("DeleteExpressionToolTip"));
upOneButton.setToolTipText(bundle.getString("MoveUpOneToolTip"));
downOneButton.setToolTipText(bundle.getString("MoveDownOneToolTip"));
applyButton.setToolTipText(bundle.getString("ApplyTitle"));
addExpButton.setOpaque(false);
deleteExpButton.setOpaque(false);
upOneButton.setOpaque(false);
downOneButton.setOpaque(false);
applyButton.setOpaque(false);
addExpButton.setFocusPainted(false);
deleteExpButton.setFocusPainted(false);
upOneButton.setFocusPainted(false);
downOneButton.setFocusPainted(false);
applyButton.setFocusPainted(false);
addExpButton.setSize(200,200);
addExpButton.setContentAreaFilled(true);
deleteExpButton.setSize(200,200);
deleteExpButton.setContentAreaFilled(true);
upOneButton.setSize(200,10);
upOneButton.setContentAreaFilled(true);
downOneButton.setSize(200,10);
downOneButton.setContentAreaFilled(true);
applyButton.setSize(200,10);
applyButton.setContentAreaFilled(true);
applyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!valueTextField.getText().isEmpty() && !displayTextField.getText().isEmpty() &&
multiViewManifestation.getSelectedExpression() != null) {
MultiRuleExpression newExp = new MultiRuleExpression(setLogicStrings.get(ifComboBox.getSelectedItem().toString()),
multiViewManifestation.getSelectedExpression().getPUIs().split(MultiRuleExpression.parameterDelimiter,0),
parameterComboBox.getSelectedItem().toString().contains(":") ? parameterComboBox.getSelectedItem().toString() :
bundle.getString("DataFeedPrefix")+parameterComboBox.getSelectedItem().toString(),
opComboBox.getSelectedItem().toString(),
valueTextField.getText(),
displayTextField.getText(),
ruleNameTextField.getText());
controller.notifyRuleUpdated(multiViewManifestation.getExpressions().indexOf(multiViewManifestation.getSelectedExpression()),
multiViewManifestation.getExpressions(),
newExp);
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
applyButton.setEnabled(false);
multiViewManifestation.setSelectedExpression(newExp);
}
}
});
applyButton.setEnabled(false);
addExpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listenersEnabled){
ruleTablePanel.setVisible(true);
bottomPanel.setVisible(true);
String valueText = valueTextField.getText().isEmpty() ? bundle.getString("DefaultValue") : valueTextField.getText();
String displayText = displayTextField.getText().isEmpty() ? bundle.getString("DefaultDisplayValue") : displayTextField.getText();
MultiRuleExpression newExp = new MultiRuleExpression(setLogicStrings.get(ifComboBox.getSelectedItem().toString()),
addDataFeedPrefixes(getTelemetryIDs()),
parameterComboBox.getSelectedItem().toString().contains(":") ? parameterComboBox.getSelectedItem().toString() :
bundle.getString("DataFeedPrefix")+parameterComboBox.getSelectedItem().toString(),
opComboBox.getSelectedItem().toString(),
valueText,
displayText,
ruleNameTextField.getText());
controller.notifyExpressionAdded(newExp,
multiViewManifestation.getExpressions());
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
multiViewManifestation.setSelectedExpression(newExp);
loadRuleButtonSettings();
}
}
});
deleteExpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MultiRuleExpression selectedExpression = multiViewManifestation.getSelectedExpression();
if (listenersEnabled){
controller.notifyExpressionDeleted(selectedExpression, multiViewManifestation.getExpressions());
if (multiViewManifestation.getExpressions().size() == 0) {
ruleTablePanel.setVisible(false);
bottomPanel.setVisible(false);
}
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
loadRuleButtonSettings();
}
}
});
upOneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MultiRuleExpression selectedExpression = multiViewManifestation.getSelectedExpression();
if (listenersEnabled){
controller.notifyMovedUpOne(selectedExpression, multiViewManifestation.getExpressions());
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
multiViewManifestation.setSelectedExpression(selectedExpression);
}
}
});
downOneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MultiRuleExpression selectedExpression = multiViewManifestation.getSelectedExpression();
if (listenersEnabled){
controller.notifyMovedDownOne(selectedExpression, multiViewManifestation.getExpressions());
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
multiViewManifestation.setSelectedExpression(selectedExpression);
}
}
});
ruleResultTextField = new JTextField();
ruleResultTextField.setEditable(false);
ruleResultTextField.setBackground(Color.WHITE);
ruleResultTextField.setPreferredSize(new Dimension(100,20));
GridBagConstraints addExpButtonConstraints = new GridBagConstraints();
addExpButtonConstraints.fill = GridBagConstraints.NONE;
addExpButtonConstraints.anchor = GridBagConstraints.LINE_START;
addExpButtonConstraints.weighty = 1;
addExpButtonConstraints.weightx = 0;
addExpButtonConstraints.ipadx = 1;
addExpButtonConstraints.gridx = 0;
addExpButtonConstraints.gridy = 0;
creationInnerPanel.add(addExpButton, addExpButtonConstraints);
GridBagConstraints deleteExpButtonConstraints = new GridBagConstraints();
deleteExpButtonConstraints.fill = GridBagConstraints.NONE;
deleteExpButtonConstraints.anchor = GridBagConstraints.LINE_START;
deleteExpButtonConstraints.weighty = 1;
deleteExpButtonConstraints.weightx = 0;
deleteExpButtonConstraints.ipadx = 1;
deleteExpButtonConstraints.gridx = 1;
deleteExpButtonConstraints.gridy = 0;
creationInnerPanel.add(deleteExpButton, deleteExpButtonConstraints);
GridBagConstraints addAboveButtonConstraints = new GridBagConstraints();
addAboveButtonConstraints.fill = GridBagConstraints.NONE;
addAboveButtonConstraints.anchor = GridBagConstraints.LINE_START;
addAboveButtonConstraints.weighty = 1;
addAboveButtonConstraints.weightx = 0;
addAboveButtonConstraints.ipadx = 1;
addAboveButtonConstraints.gridx = 2;
addAboveButtonConstraints.gridy = 0;
creationInnerPanel.add(upOneButton, addAboveButtonConstraints);
GridBagConstraints addBelowButtonConstraints = new GridBagConstraints();
addBelowButtonConstraints.fill = GridBagConstraints.NONE;
addBelowButtonConstraints.anchor = GridBagConstraints.LINE_START;
addBelowButtonConstraints.weighty = 1;
addBelowButtonConstraints.weightx = 1;
addBelowButtonConstraints.ipadx = 1;
addBelowButtonConstraints.gridx = 3;
addBelowButtonConstraints.gridy = 0;
creationInnerPanel.add(downOneButton, addBelowButtonConstraints);
GridBagConstraints checkBoxPanelConstraints = new GridBagConstraints();
checkBoxPanelConstraints.fill = GridBagConstraints.NONE;
checkBoxPanelConstraints.anchor = GridBagConstraints.LINE_START;
checkBoxPanelConstraints.weighty = 1;
checkBoxPanelConstraints.weightx = 1;
checkBoxPanelConstraints.ipadx = 1;
checkBoxPanelConstraints.gridx = 5;
checkBoxPanelConstraints.gridy = 0;
creationInnerPanel.add(checkBoxPanel, checkBoxPanelConstraints);
if (includeRuleTable) {
GridBagConstraints rulePanelConstraints = new GridBagConstraints();
rulePanelConstraints.fill = GridBagConstraints.NONE;
rulePanelConstraints.anchor = GridBagConstraints.LINE_START;
rulePanelConstraints.weighty = 1;
rulePanelConstraints.weightx = 1;
rulePanelConstraints.ipadx = 1;
rulePanelConstraints.gridx = 0;
rulePanelConstraints.gridy = 2;
creationPanel.add(createRuleTablePanel(), rulePanelConstraints);
bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
bottomPanel.add(new JLabel(bundle.getString("RuleResultTitle")));
bottomPanel.add(ruleResultTextField);
bottomPanel.add(applyButton );
bottomPanel.setPreferredSize(new Dimension((int) ruleTablePanel.getPreferredSize().getWidth(),50));
GridBagConstraints rulePanelConstraints2 = new GridBagConstraints();
rulePanelConstraints2.fill = GridBagConstraints.NONE;
rulePanelConstraints2.anchor = GridBagConstraints.LINE_START;
rulePanelConstraints2.weighty = 1;
rulePanelConstraints2.weightx = 1;
rulePanelConstraints2.ipadx = 1;
rulePanelConstraints2.gridx = 0;
rulePanelConstraints2.gridy = 3;
creationPanel.add(bottomPanel, rulePanelConstraints2);
}
return creationPanel;
}
/**
* Load the currently selected rule into the controls.
*/
public void loadRule() {
if (multiViewManifestation.getSelectedExpression() != null) {
applyButtonListenersEnabled = false;
ifComboBox.setSelectedItem(multiViewManifestation.getSelectedExpression().getMultiSetLogic().getDisplayName());
parameterComboBox.removeAllItems();
for (String parameter : multiViewManifestation.getSelectedExpression().getPUIs().split(MultiRuleExpression.parameterDelimiter)) {
if (parameter.startsWith(bundle.getString("DataFeedPrefix"))){
parameterComboBox.addItem(parameter.substring(bundle.getString("DataFeedPrefix").length()));
} else {
parameterComboBox.addItem(parameter);
}
}
if (multiViewManifestation.getSelectedExpression().getMultiSetLogic().equals(SetLogic.SINGLE_PARAMETER)) {
if (multiViewManifestation.getSelectedExpression().getSinglePui().startsWith(bundle.getString("DataFeedPrefix"))){
parameterComboBox.setSelectedItem(multiViewManifestation.getSelectedExpression().getSinglePui().substring(bundle.getString("DataFeedPrefix").length()));
} else {
parameterComboBox.setSelectedItem(multiViewManifestation.getSelectedExpression().getSinglePui());
}
}
opComboBox.setSelectedItem(multiViewManifestation.getSelectedExpression().getOperator());
valueTextField.setText(multiViewManifestation.getSelectedExpression().getVal().toString());
displayTextField.setText(multiViewManifestation.getSelectedExpression().getDisplay());
displayTextField.setToolTipText(displayTextField.getText());
valueTextField.setToolTipText(valueTextField.getText());
ruleNameTextField.setText(multiViewManifestation.getSelectedExpression().getName());
ruleNameTextField.setToolTipText(ruleNameTextField.getText());
applyButtonListenersEnabled = true;
applyButton.setEnabled(false);
loadRuleButtonSettings();
}
}
private JPanel createIndeterminatePanel(){
JPanel indeterminatePanel = new JPanel();
indeterminatePanel.setLayout(new BorderLayout());
//Add title
indeterminatePanel.setBorder(BorderFactory.createTitledBorder(bundle.getString("Indeterminate")));
JPanel indeterminateInnerPanel = new JPanel();
indeterminateInnerPanel.setLayout(new GridBagLayout());
indeterminateTextField = new JTextField();
indeterminateTextField.setPreferredSize(new Dimension(150,20));
indeterminateTextField.setEditable(true);
indeterminateTextField.setText(multiViewManifestation.getMulti().getData().getFallThroughDisplayValue());
indeterminateTextField.setName(bundle.getString("Indeterminate"));
indeterminateTextField.getDocument().addDocumentListener(new IndeterminateValueListener());
indeterminateTextField.setToolTipText(indeterminateTextField.getText());
JLabel indeterminateLabel = new JLabel(bundle.getString("IndeterminateLabel"));
GridBagConstraints indeterminateFieldConstraints = new GridBagConstraints();
indeterminateFieldConstraints.fill = GridBagConstraints.NONE;
indeterminateFieldConstraints.anchor = GridBagConstraints.LINE_START;
indeterminateFieldConstraints.weighty = .25;
indeterminateFieldConstraints.ipadx = 1;
indeterminateFieldConstraints.gridx = 0;
indeterminateFieldConstraints.gridy = 0;
indeterminateInnerPanel.add(indeterminateLabel, indeterminateFieldConstraints);
GridBagConstraints indeterminateFieldConstraints2 = new GridBagConstraints();
indeterminateFieldConstraints2.fill = GridBagConstraints.NONE;
indeterminateFieldConstraints2.anchor = GridBagConstraints.LINE_START;
indeterminateFieldConstraints2.weighty = .25;
indeterminateFieldConstraints2.ipadx = 1;
indeterminateFieldConstraints2.gridx = 1;
indeterminateFieldConstraints2.gridy = 0;
indeterminateInnerPanel.add(indeterminateTextField, indeterminateFieldConstraints2);
indeterminatePanel.add(indeterminateInnerPanel, BorderLayout.WEST);
return indeterminatePanel;
}
/** Set the value of the rule result text field.
* @param result result of the rule execution
*/
public void setRuleResultField(String result) {
ruleResultTextField.setText(result);
ruleResultTextField.setToolTipText(ruleResultTextField.getText());
}
private class IndeterminateValueListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
indeterminateTextField.setToolTipText(indeterminateTextField.getText());
multiViewManifestation.getMulti().getData().setFallThroughDisplayValue(indeterminateTextField.getText());
multiViewManifestation.fireFocusPersist();
}
public void removeUpdate(DocumentEvent e) {
indeterminateTextField.setToolTipText(indeterminateTextField.getText());
multiViewManifestation.getMulti().getData().setFallThroughDisplayValue(indeterminateTextField.getText());
multiViewManifestation.fireFocusPersist();
}
@Override
public void changedUpdate(DocumentEvent e) {
}
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
535 | passThroughCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AbstractButton abstractButton = (AbstractButton) e.getSource();
if (abstractButton.getModel().isSelected()) {
multiViewManifestation.getMulti().getData().setPassThrough(true);
multiViewManifestation.getMulti().getData().setPassThroughParameterId(multiViewManifestation.getTelemetry().get(0).getCapability(FeedProvider.class).getSubscriptionId());
addExpButton.setEnabled(false);
deleteExpButton.setEnabled(false);
upOneButton.setEnabled(false);
downOneButton.setEnabled(false);
} else {
multiViewManifestation.getMulti().getData().setPassThrough(false);
multiViewManifestation.getMulti().getData().setPassThroughParameterId(null);
addExpButton.setEnabled(true);
deleteExpButton.setEnabled(true);
upOneButton.setEnabled(true);
downOneButton.setEnabled(true);
}
multiViewManifestation.fireFocusPersist();
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
536 | applyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!valueTextField.getText().isEmpty() && !displayTextField.getText().isEmpty() &&
multiViewManifestation.getSelectedExpression() != null) {
MultiRuleExpression newExp = new MultiRuleExpression(setLogicStrings.get(ifComboBox.getSelectedItem().toString()),
multiViewManifestation.getSelectedExpression().getPUIs().split(MultiRuleExpression.parameterDelimiter,0),
parameterComboBox.getSelectedItem().toString().contains(":") ? parameterComboBox.getSelectedItem().toString() :
bundle.getString("DataFeedPrefix")+parameterComboBox.getSelectedItem().toString(),
opComboBox.getSelectedItem().toString(),
valueTextField.getText(),
displayTextField.getText(),
ruleNameTextField.getText());
controller.notifyRuleUpdated(multiViewManifestation.getExpressions().indexOf(multiViewManifestation.getSelectedExpression()),
multiViewManifestation.getExpressions(),
newExp);
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
applyButton.setEnabled(false);
multiViewManifestation.setSelectedExpression(newExp);
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
537 | addExpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listenersEnabled){
ruleTablePanel.setVisible(true);
bottomPanel.setVisible(true);
String valueText = valueTextField.getText().isEmpty() ? bundle.getString("DefaultValue") : valueTextField.getText();
String displayText = displayTextField.getText().isEmpty() ? bundle.getString("DefaultDisplayValue") : displayTextField.getText();
MultiRuleExpression newExp = new MultiRuleExpression(setLogicStrings.get(ifComboBox.getSelectedItem().toString()),
addDataFeedPrefixes(getTelemetryIDs()),
parameterComboBox.getSelectedItem().toString().contains(":") ? parameterComboBox.getSelectedItem().toString() :
bundle.getString("DataFeedPrefix")+parameterComboBox.getSelectedItem().toString(),
opComboBox.getSelectedItem().toString(),
valueText,
displayText,
ruleNameTextField.getText());
controller.notifyExpressionAdded(newExp,
multiViewManifestation.getExpressions());
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
multiViewManifestation.setSelectedExpression(newExp);
loadRuleButtonSettings();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
538 | deleteExpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MultiRuleExpression selectedExpression = multiViewManifestation.getSelectedExpression();
if (listenersEnabled){
controller.notifyExpressionDeleted(selectedExpression, multiViewManifestation.getExpressions());
if (multiViewManifestation.getExpressions().size() == 0) {
ruleTablePanel.setVisible(false);
bottomPanel.setVisible(false);
}
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
loadRuleButtonSettings();
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
539 | upOneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MultiRuleExpression selectedExpression = multiViewManifestation.getSelectedExpression();
if (listenersEnabled){
controller.notifyMovedUpOne(selectedExpression, multiViewManifestation.getExpressions());
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
multiViewManifestation.setSelectedExpression(selectedExpression);
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
540 | downOneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MultiRuleExpression selectedExpression = multiViewManifestation.getSelectedExpression();
if (listenersEnabled){
controller.notifyMovedDownOne(selectedExpression, multiViewManifestation.getExpressions());
multiViewManifestation.getMulti().getData().setCode(multiViewManifestation.getExpressions().toString());
multiViewManifestation.fireFocusPersist();
multiViewManifestation.setSelectedExpression(selectedExpression);
}
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
541 | private class ApplyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (displayTextField.getText().isEmpty() || valueTextField.getText().isEmpty()) {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(false);
}
applyButton.setToolTipText("Rule value or display fields do not contain valid values");
ruleNameTextField.setToolTipText(ruleNameTextField.getText());
} else {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(true);
}
applyButton.setToolTipText("Apply changes to this rule");
}
displayTextField.setToolTipText(displayTextField.getText());
valueTextField.setToolTipText(valueTextField.getText());
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
542 | private class ApplyButtonListener implements DocumentListener {
public void insertUpdate(DocumentEvent event) {
if (displayTextField.getText().isEmpty() || valueTextField.getText().isEmpty()) {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(false);
}
applyButton.setToolTipText("Rule value or display fields do not contain valid values");
ruleNameTextField.setToolTipText(ruleNameTextField.getText());
} else {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(true);
}
applyButton.setToolTipText("Apply changes to this rule");
}
displayTextField.setToolTipText(displayTextField.getText());
valueTextField.setToolTipText(valueTextField.getText());
}
public void removeUpdate(DocumentEvent event) {
if (displayTextField.getText().isEmpty() || valueTextField.getText().isEmpty()) {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(false);
}
applyButton.setToolTipText("Rule value or display fields do not contain valid values");
} else {
if (applyButtonListenersEnabled) {
applyButton.setEnabled(true);
}
applyButton.setToolTipText("Apply changes to this rule");
}
displayTextField.setToolTipText(displayTextField.getText());
valueTextField.setToolTipText(valueTextField.getText());
}
@Override
public void changedUpdate(DocumentEvent e) {
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
543 | private class IndeterminateValueListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
indeterminateTextField.setToolTipText(indeterminateTextField.getText());
multiViewManifestation.getMulti().getData().setFallThroughDisplayValue(indeterminateTextField.getText());
multiViewManifestation.fireFocusPersist();
}
public void removeUpdate(DocumentEvent e) {
indeterminateTextField.setToolTipText(indeterminateTextField.getText());
multiViewManifestation.getMulti().getData().setFallThroughDisplayValue(indeterminateTextField.getText());
multiViewManifestation.fireFocusPersist();
}
@Override
public void changedUpdate(DocumentEvent e) {
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiExpressionsFormattingControlsPanel.java |
544 | public class MultiRuleExpression extends Expression {
/**
* Delimiter to use to separate parameter IDs.
*/
public static final String parameterDelimiter = ";";
private SetLogic multiSetLogic;
private List<String> puiList = new ArrayList<String>();
private String singlePui = "";
private String name = "";
/**
* Expression initialization based upon operation, value, and display.
* @param setLogic the logic for this rule
* @param puis an array of pui IDs for this rule
* @param singlePui a single pui to use for this rule
* @param op operation.
* @param val value.
* @param dis display name.
* @param name the name of the rule
*/
public MultiRuleExpression(SetLogic setLogic, String[] puis, String singlePui, String op,
String val, String dis, String name){
super(op, val, dis);
this.setMultiSetLogic(setLogic);
this.name = name;
this.singlePui = singlePui;
for (String pui : puis) {
puiList.add(pui);
}
}
/** Get all the parameter IDs associated with this rule.
* @return a delimited list of parameter IDs
*/
public String getPUIs() {
StringBuilder sb = new StringBuilder();
for (String pui : puiList) {
sb.append(pui+ parameterDelimiter);
}
return sb.toString();
}
/**
* Create a Multi rule expression.
*/
public MultiRuleExpression() {
super();
this.multiSetLogic = SetLogic.SINGLE_PARAMETER;
}
/** Return the logic used to combine values compared by this rule.
* @return multiSetLogic
*/
public SetLogic getMultiSetLogic() {
return multiSetLogic;
}
/** Set the logic used to combine values compared by this rule.
* @param multiSetLogic the set logic used by this rule
*/
public void setMultiSetLogic(SetLogic multiSetLogic) {
this.multiSetLogic = multiSetLogic;
}
/** Get the name of this rule.
* @return name the name of this rule
*/
public String getName() {
return name;
}
/** Set the name of this rule.
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/** Get the single parameter ID when the set logic requires it.
* @return singlePui
*/
public String getSinglePui() {
return singlePui;
}
/** Set the single parameter ID when the set logic requires it.
* @param singlePui set the single parameter ID
*/
public void setSinglePui(String singlePui) {
this.singlePui = singlePui;
}
/** Enumeration of rule set logic.
* @author dcberrio
*
*/
public enum SetLogic {
/** Use a single parameter.
* @author dcberrio
*
*/
SINGLE_PARAMETER ("Single parameter") {
/** Test whether a string matches the set logic.
* @param setLogic the set logic to match
* @return boolean matching or not
*/
public boolean matches(String setLogic) {
return "SINGLE_PARAMETER".equals(setLogic);
}
},
/** More than 1 parameter.
* @author dcberrio
*
*/
MORE_THAN_ONE_PARAMETER ("More than 1 parameter") {
/** Test whether a string matches the set logic.
* @param setLogic the set logic to match
* @return boolean matching or not
*/
public boolean matches(String setLogic) {
return "MORE_THAN_ONE_PARAMETER".equals(setLogic);
}
},
/** All parameters.
* @author dcberrio
*
*/
ALL_PARAMETERS ("All parameters"){
/** Test whether a string matches the set logic.
* @param setLogic the set logic to match
* @return boolean matching or not
*/
public boolean matches(String setLogic) {
return "ALL_PARAMETERS".equals(setLogic);
}
};
private String displayName;
private SetLogic(String name) {
this.setDisplayName(name);
}
/** Get the display name.
* @return displayName the name of this rule
*/
public String getDisplayName() {
return displayName;
}
/** Set the display name.
* @param displayName the name of the rule
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiRuleExpression.java |
545 | public enum SetLogic {
/** Use a single parameter.
* @author dcberrio
*
*/
SINGLE_PARAMETER ("Single parameter") {
/** Test whether a string matches the set logic.
* @param setLogic the set logic to match
* @return boolean matching or not
*/
public boolean matches(String setLogic) {
return "SINGLE_PARAMETER".equals(setLogic);
}
},
/** More than 1 parameter.
* @author dcberrio
*
*/
MORE_THAN_ONE_PARAMETER ("More than 1 parameter") {
/** Test whether a string matches the set logic.
* @param setLogic the set logic to match
* @return boolean matching or not
*/
public boolean matches(String setLogic) {
return "MORE_THAN_ONE_PARAMETER".equals(setLogic);
}
},
/** All parameters.
* @author dcberrio
*
*/
ALL_PARAMETERS ("All parameters"){
/** Test whether a string matches the set logic.
* @param setLogic the set logic to match
* @return boolean matching or not
*/
public boolean matches(String setLogic) {
return "ALL_PARAMETERS".equals(setLogic);
}
};
private String displayName;
private SetLogic(String name) {
this.setDisplayName(name);
}
/** Get the display name.
* @return displayName the name of this rule
*/
public String getDisplayName() {
return displayName;
}
/** Set the display name.
* @param displayName the name of the rule
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiRuleExpression.java |
546 | SINGLE_PARAMETER ("Single parameter") {
/** Test whether a string matches the set logic.
* @param setLogic the set logic to match
* @return boolean matching or not
*/
public boolean matches(String setLogic) {
return "SINGLE_PARAMETER".equals(setLogic);
}
}, | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiRuleExpression.java |
547 | MORE_THAN_ONE_PARAMETER ("More than 1 parameter") {
/** Test whether a string matches the set logic.
* @param setLogic the set logic to match
* @return boolean matching or not
*/
public boolean matches(String setLogic) {
return "MORE_THAN_ONE_PARAMETER".equals(setLogic);
}
}, | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiRuleExpression.java |
548 | ALL_PARAMETERS ("All parameters"){
/** Test whether a string matches the set logic.
* @param setLogic the set logic to match
* @return boolean matching or not
*/
public boolean matches(String setLogic) {
return "ALL_PARAMETERS".equals(setLogic);
}
}; | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiRuleExpression.java |
549 | public class MultiRuleExpressionList {
private ArrayList <MultiRuleExpression> expList;
/**
* Expression list constructor.
* @param code the code.
*/
public MultiRuleExpressionList(String code) {
expList = compile(code);
}
/**
* Compiles the expression.
* @param code the code.
* @return array list of expressions.
*/
public ArrayList<MultiRuleExpression> compile(String code){
ArrayList <MultiRuleExpression> expressions = new ArrayList <MultiRuleExpression> ();
Matcher m = MultiEvaluator.multiExpressionPattern.matcher(code);
while (m.find()){
assert m.groupCount() == 7 : "Seven matching groups should be discovered: found " + m.groupCount();
String singleOrAll = m.group(1);
String puis = m.group(2);
String[] puiList = puis.split(MultiRuleExpression.parameterDelimiter, 0);
String pui = m.group(3);
String relation = m.group(4);
String value = m.group(5);
String display = m.group(6);
String name = m.group(7);
expressions.add(new MultiRuleExpression(Enum.valueOf(MultiRuleExpression.SetLogic.class, singleOrAll),
puiList, pui, relation, value, display, name));
}
return expressions;
}
/**
* Gets the size of the expression list.
* @return the size number.
*/
public int size() {
return expList.size();
}
/**
* Gets the index of the expression.
* @param exp expression.
* @return index number.
*/
public int indexOf (MultiRuleExpression exp) {
return expList.indexOf(exp);
}
/**
* Gets the expression based on the index.
* @param index number.
* @return expression.
*/
public MultiRuleExpression getExp (int index) {
return expList.get(index);
}
/**
* Adds the expression to the list.
* @param exp expression.
*/
public void addExp (MultiRuleExpression exp) {
expList.add(exp);
}
/**
* Adds the expression to the list based on the index number and expression object.
* @param index number.
* @param exp expression object.
*/
public void addExp (int index, MultiRuleExpression exp) {
expList.add(index, exp);
}
/**
* Updates the expression in the list based on the index number and expression object.
* @param index number.
* @param exp expression object.
*/
public void updateExp (int index, MultiRuleExpression exp) {
expList.remove(index);
expList.add(index, exp);
}
/**
* Deletes the expression.
* @param exp expression.
*/
public void deleteExp (MultiRuleExpression exp) {
int index;
if (expList != null && expList.contains(exp)) {
index = expList.indexOf(exp);
expList.remove(index);
}
}
/**
* Moves the expression.
* @param moveTo index.
* @param expSelected selected expression.
*/
public void move (int moveTo, MultiRuleExpression expSelected) {
MultiRuleExpression temp = expSelected;
int currentIndex;
if (expList.contains(expSelected)){
currentIndex = expList.indexOf(expSelected);
//case for moving to bottom
if (moveTo == expList.size()-1){
expList.remove(currentIndex);
expList.add(temp);
}
else {
expList.remove(currentIndex);
expList.add(moveTo, temp);
}
}
}
@Override
public String toString(){
String expressions = "";
MultiRuleExpression temp;
String exp;
for (int i = 0; i < expList.size(); i++){
temp = expList.get(i);
exp = temp.getMultiSetLogic().toString() +
"\t" + temp.getPUIs() +
"\t" + temp.getSinglePui() +
"\t" + temp.getOperator() +
"\t" + temp.getVal() +
"\t" + temp.getDisplay() +
"\t" + temp.getName() + "|";
expressions += exp;
}
return expressions;
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiRuleExpressionList.java |
550 | @SuppressWarnings("serial")
public class MultiViewManifestation extends FeedView {
private static final ResourceBundle bundle = ResourceBundle.getBundle("MultiComponent");
private static final Logger logger = LoggerFactory.getLogger(MultiViewManifestation.class);
/** Expression view role name. */
public static final String VIEW_NAME = bundle.getString("MultiViewRoleName");
private MultiRuleExpression selectedExpression;
private MultiRuleExpressionList currentExpressions;
private ArrayList<AbstractComponent> telemetryElements;
private AbstractComponent selectedTelemetry;
private final MultiComponent multiComponent;
private MultiExpressionsFormattingControlsPanel controlPanel;
private final AtomicReference<Collection<FeedProvider>> feedProvidersRef = new AtomicReference<Collection<FeedProvider>>(Collections.<FeedProvider>emptyList());
private Map<String, TimeConversion> timeConversionMap = new HashMap<String, TimeConversion>();
@SuppressWarnings("unused")
private MultiRuleExpressionsTableModel expModel;
/** The telemetry model. */
public TelemetryModel telModel;
private JTable expressionsTable;
private JTable telemetryTable;
private JPanel expressionsPanel;
private JLabel resultOutput;
private Border componentBorder = null;
/**
* The multi-input expression view manifestation initialization.
* @param ac the component.
* @param vi the view info.
*/
public MultiViewManifestation(AbstractComponent ac, ViewInfo vi) {
super(ac,vi);
this.multiComponent = getManifestedComponent().getCapability(MultiComponent.class);
this.selectedExpression = new MultiRuleExpression();
this.currentExpressions = new MultiRuleExpressionList(multiComponent.getData().getCode());
this.telemetryElements = new ArrayList<AbstractComponent>();
refreshTelemetry();
updateFeedProviders();
expressionsPanel = new JPanel();
expressionsPanel.getAccessibleContext().setAccessibleName("Expressions");
if (getColor("border") != null) {
componentBorder = BorderFactory.createLineBorder(getColor("border"));
}
load();
expressionsPanel.setAutoscrolls(true);
}
private Color getColor(String name) {
return UIManager.getColor(name);
}
/**
* Gets the multi-input evaluator component.
* @return the multi-input evaluator component.
*/
public MultiComponent getMulti() {
return multiComponent;
}
/**
* Gets the multi-input expression list.
* @return the multi-input expression list.
*/
public MultiRuleExpressionList getExpressions(){
return currentExpressions;
}
/**
* Gets the array list of telemetry components.
* @return array list of telemetry components.
*/
public ArrayList<AbstractComponent> getTelemetry(){
return telemetryElements;
}
private void refreshTelemetry(){
telemetryElements.clear();
for (AbstractComponent component : getManifestedComponent().getComponents()){
if (component.getCapability(FeedProvider.class) != null){
telemetryElements.add(component);
}
}
}
/**
* Clear the list of multi-input expressions from the expressions table.
*/
public void refreshRuleExpressions(){
((MultiRuleExpressionsTableModel)expressionsTable.getModel()).clearModel();
}
private void load() {
buildGUI();
}
@SuppressWarnings("unused")
private boolean containsChildComponent(AbstractComponent parentComponent, String childComponentId) {
for (AbstractComponent childComponent : parentComponent.getComponents()) {
if (childComponentId.equals(childComponent.getComponentId())){
return true;
}
}
return false;
}
private void buildGUI() {
//show associated telemetry element, table of expressions, test value
setLayout(new GridBagLayout());
//Input area for test value at top of view
JLabel result = new JLabel("Result: ");
resultOutput = new JLabel();
//Add table of expressions
expressionsTable = new JTable(expModel = new MultiRuleExpressionsTableModel());
expressionsTable.setAutoCreateColumnsFromModel(true);
expressionsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
expressionsTable.setRowSelectionAllowed(true);
expressionsTable.getColumnModel().getColumn(0).setWidth(20);
expressionsTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
expressionsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
controlPanel.loadRule();
}
});
JScrollPane expressionsTableScrollPane = new JScrollPane(expressionsTable,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
expressionsTableScrollPane.setPreferredSize(new Dimension(300, 150));
GridBagConstraints titleConstraints = getConstraints(0,1);
titleConstraints.gridwidth = 3;
titleConstraints.fill = GridBagConstraints.HORIZONTAL;
titleConstraints.gridheight = 1;
titleConstraints.insets = new Insets(1,9,9,9);
titleConstraints.weightx = 1;
titleConstraints.weighty = .7;
add(new JLabel(multiComponent.getDisplayName() + " " + bundle.getString("RuleTableTitleLabel")), titleConstraints);
GridBagConstraints eTableConstraints = getConstraints(0,2);
eTableConstraints.gridwidth = 3;
eTableConstraints.fill = GridBagConstraints.HORIZONTAL;
eTableConstraints.gridheight = 1;
eTableConstraints.insets = new Insets(1,9,9,9);
eTableConstraints.weightx = 1;
eTableConstraints.weighty = .1;
add(expressionsTableScrollPane, eTableConstraints);
GridBagConstraints paramTableTitleConstraints = getConstraints(0,3);
paramTableTitleConstraints.gridwidth = 3;
paramTableTitleConstraints.fill = GridBagConstraints.HORIZONTAL;
paramTableTitleConstraints.gridheight = 1;
paramTableTitleConstraints.insets = new Insets(1,9,9,9);
paramTableTitleConstraints.weightx = 1;
paramTableTitleConstraints.weighty = .1;
add(new JLabel(multiComponent.getDisplayName() + " " + bundle.getString("ParamTableTitleLabel")), paramTableTitleConstraints);
//Add table of telemetry elements
telemetryTable = new JTable(telModel = new TelemetryModel());
telemetryTable.setAutoCreateColumnsFromModel(true);
telemetryTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
telemetryTable.setRowSelectionAllowed(true);
telemetryTable.setAutoCreateRowSorter(true);
DefaultTableCellRenderer renderer = new
DefaultTableCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.CENTER);
TableColumn tc = telemetryTable.getColumn(bundle.getString("currentValueLabel"));
tc.setCellRenderer(renderer);
JScrollPane telemetryTableScrollPane = new JScrollPane(telemetryTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
telemetryTableScrollPane.setPreferredSize(new Dimension(300, 150));
if (componentBorder != null) {
expressionsTableScrollPane.setBorder(componentBorder);
telemetryTableScrollPane.setBorder(componentBorder);
}
GridBagConstraints tTableConstraints = getConstraints(0,7);
tTableConstraints.gridwidth = 3;
tTableConstraints.gridheight = 1;
tTableConstraints.insets = new Insets(1,9,9,9);
tTableConstraints.weightx = 1;
tTableConstraints.weighty = .3;
tTableConstraints.anchor = GridBagConstraints.WEST;
tTableConstraints.fill = GridBagConstraints.HORIZONTAL;
add(telemetryTableScrollPane, tTableConstraints);
//Add results
GridBagConstraints rConstraints = getConstraints(0,12);
rConstraints.insets = new Insets(3,9,5,1);
add(result, rConstraints);
GridBagConstraints rOutputConstraints = getConstraints(1,12);
rOutputConstraints.insets = new Insets (3,1,5,9);
add(resultOutput, rOutputConstraints);
}
private GridBagConstraints getConstraints(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = x == 0 ? 0 : 1;
gbc.weighty = 0;
gbc.insets = new Insets(0,9,4,9);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTHWEST;
return gbc;
}
/**
* Evaluates the result.
* @param value the string value.
* @return the evaluated result.
*/
public String evaluate(String value){
MultiEvaluator e = new MultiEvaluator();
e.compile(multiComponent.getData().getCode());
return null;
}
/**
* Expressions table model.
*/
@SuppressWarnings("unchecked")
public class MultiRuleExpressionsTableModel extends AbstractTableModel {
private MultiRuleExpressionList eList = currentExpressions;
private List<String> numbers = new ArrayList<String>();
private List<String> rulesNames = new ArrayList<String>();
private List<String> displayedStrings = new ArrayList<String>();
private List<List<String>> lists = Arrays.asList(numbers, rulesNames, displayedStrings);
private final List<String> columnNames = new ArrayList<String>();
/**
* Initializes the expression model.
*/
MultiRuleExpressionsTableModel(){
columnNames.add(bundle.getString("NumberLabel"));
columnNames.add(bundle.getString("RuleName"));
columnNames.add(bundle.getString("DisplayedString"));
loadExpressions();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return eList.size();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex){
List<String> list = getListForColumn(columnIndex);
String value = list.get(rowIndex);
return columnIndex == 3 ? Double.valueOf(value) : value;
}
private List<String> getListForColumn(int col){
return lists.get(col);
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col==1 && value != null){
eList.getExp(row).setName(value.toString());
}
if (col==2 && value != null){
eList.getExp(row).setDisplay(value.toString());
}
multiComponent.getData().setCode(eList.toString());
fireTableCellUpdated(row, col);
fireFocusPersist();
}
private void loadExpressions(){
MultiRuleExpression e;
for (int i = 0; i < eList.size(); i++){
e = eList.getExp(i);
numbers.add(Integer.valueOf(i+1).toString());
rulesNames.add(e.getName());
displayedStrings.add(e.getDisplay());
}
}
/**
* Clears the model.
*/
public void clearModel() {
numbers.clear();
rulesNames.clear();
displayedStrings.clear();
loadExpressions();
fireTableDataChanged();
}
}
/**
* Telemetry model.
*/
@SuppressWarnings("unchecked")
class TelemetryModel extends AbstractTableModel{
private List<String> pui = new ArrayList<String>();
private List<String> baseDisplay = new ArrayList<String>();
private List<String> currentValues = new ArrayList<String>();
private List<List<String>> lists = Arrays.asList(pui, baseDisplay, currentValues);
private final List<String> columnNames = new ArrayList<String>();
/**
* Initializes the telemetry model.
*/
TelemetryModel(){
columnNames.add(bundle.getString("PuiLabel"));
columnNames.add(bundle.getString("BaseDisplayLabel"));
columnNames.add(bundle.getString("currentValueLabel"));
loadTelemetry();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return telemetryElements.size();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex){
List<String> list = getListForColumn(columnIndex);
if (list.size() == 0) {
return "";
}
return list.get(rowIndex);
}
private List<String> getListForColumn(int col){
return lists.get(col);
}
/**
* Loads the telemetry.
*/
protected void loadTelemetry(){
refreshTelemetry();
for (AbstractComponent ac : telemetryElements){
pui.add(ac.getExternalKey());
baseDisplay.add(ac.getDisplayName());
currentValues.add("");
}
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col==2 && value != null) {
currentValues.set(row, value.toString());
}
fireTableCellUpdated(row, col);
}
/**
* Clears the telemetry model.
*/
public void clearModel() {
pui.clear();
baseDisplay.clear();
currentValues.clear();
loadTelemetry();
controlPanel.updatePassThroughControl();
fireTableDataChanged();
}
}
@Override
protected JComponent initializeControlManifestation() {
//Set canvas control
this.controlPanel = new MultiExpressionsFormattingControlsPanel(this);
Dimension d = controlPanel.getMinimumSize();
d.setSize(0,0);
controlPanel.setMinimumSize(d);
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
pane.setOneTouchExpandable(true);
pane.setBorder(BorderFactory.createEmptyBorder());
JScrollPane controlScrollPane = new JScrollPane(controlPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
return controlScrollPane;
}
/**
* Gets the selected multi-input expression.
* @return the multi-input expression.
*/
public MultiRuleExpression getSelectedExpression(){
int rows = expressionsTable.getSelectedRowCount();
if (rows == 1){
selectedExpression = currentExpressions.getExp(expressionsTable.getSelectedRow());
}
else {
selectedExpression = null;
}
return selectedExpression;
}
/**
* Sets the selected expression.
* @param exp the expression to set
*/
public void setSelectedExpression(MultiRuleExpression exp){
int index = getExpressions().indexOf(exp);
expressionsTable.getSelectionModel().setSelectionInterval(index, index);
selectedExpression = exp;
}
/**
* Gets the selected telemetry.
* @return the component.
*/
public AbstractComponent getSelectedTelemetry(){
int row = telemetryTable.getSelectedRowCount();
if (row == 1){
selectedTelemetry = telemetryElements.get(telemetryTable.getSelectedRow());
}
else {
selectedTelemetry = null;
}
return selectedTelemetry;
}
/**
* Saves the manifested component.
*/
public void fireFocusPersist(){
if (!isLocked()) {
getManifestedComponent().save();
}
}
/**
* Fires the selection property changes.
*/
public void fireManifestationChanged() {
firePropertyChange(SelectionProvider.SELECTION_CHANGED_PROP, null, getSelectedExpression());
}
@Override
public void updateMonitoredGUI(){
((MultiRuleExpressionsTableModel)expressionsTable.getModel()).clearModel();
((TelemetryModel)telemetryTable.getModel()).clearModel();
controlPanel.loadRuleButtonSettings();
updateFeedProviders();
}
@Override
public void updateMonitoredGUI(AddChildEvent event) {
((TelemetryModel)telemetryTable.getModel()).clearModel();
controlPanel.loadRuleButtonSettings();
updateFeedProviders();
}
@Override
public void updateMonitoredGUI(RemoveChildEvent event) {
((TelemetryModel)telemetryTable.getModel()).clearModel();
controlPanel.loadRuleButtonSettings();
updateFeedProviders();
}
private List<FeedProvider> getFeedProviders(AbstractComponent component) {
List<FeedProvider> feedProviders = new ArrayList<FeedProvider>(
component.getComponents().size());
for (AbstractComponent referencedComponent : component.getComponents()) {
FeedProvider fp = referencedComponent.getCapability(
FeedProvider.class);
if (fp != null) {
feedProviders.add(fp);
}
}
return feedProviders;
}
private void updateFeedProviders() {
ArrayList<FeedProvider> feedProviders = new ArrayList<FeedProvider>();
timeConversionMap.clear();
for (AbstractComponent component : telemetryElements) {
if (component != null) {
FeedProvider fp = getFeedProvider(component);
if (fp != null) {
feedProviders.add(fp);
TimeConversion tc = component.getCapability(TimeConversion.class);
if (tc != null) {
timeConversionMap.put(fp.getSubscriptionId(), tc);
}
} else {
if (component.getCapability(Evaluator.class) != null) {
for (AbstractComponent referencedComponent : component.getComponents()) {
fp = getFeedProvider(referencedComponent);
if (fp != null) {
feedProviders.add(fp);
}
}
}
}
}
}
feedProviders.trimToSize();
feedProvidersRef.set(feedProviders);
}
@Override
public void updateFromFeed(Map<String, List<Map<String, String>>> data) {
if (data != null) {
Collection<FeedProvider> feeds = getVisibleFeedProviders();
Map<String,Double> valuesMap = new HashMap<String,Double>();
for (FeedProvider provider : feeds) {
String feedId = provider.getSubscriptionId();
List<Map<String, String>> dataForThisFeed = data
.get(feedId);
if (dataForThisFeed != null && !dataForThisFeed.isEmpty()) {
// Process the first value for this feed.
Map<String, String> entry = dataForThisFeed
.get(dataForThisFeed.size() - 1);
try {
RenderingInfo ri = provider.getRenderingInfo(entry);
Object value = ri.getValueText();
valuesMap.put(feedId,Double.valueOf(ri.getValueText()));;
for (AbstractComponent parameter : telemetryElements) {
FeedProvider fp = parameter.getCapability(FeedProvider.class);
if (fp != null && feedId.equals(fp.getSubscriptionId())) {
telemetryTable.getModel().setValueAt(value, telemetryElements.indexOf(parameter), 2);
}
}
} catch (ClassCastException ex) {
logger.error("Feed data entry of unexpected type",
ex);
} catch (NumberFormatException ex) {
logger.error(
"Feed data entry does not contain parsable value",
ex);
}
}
}
//Update Multi Result in Manifestation
FeedProvider.RenderingInfo multiValueInfo = getMulti().
getCapability(Evaluator.class).evaluate(data,
getFeedProviders(getMulti()));
if (multiValueInfo != null) {
resultOutput.setText(multiValueInfo.getValueText() + multiValueInfo.getStatusText());
resultOutput.setForeground(multiValueInfo.getValueColor());
} else {
resultOutput.setText("");
}
// Update SingleRule Result in control panel
if (getSelectedExpression() != null) {
MultiExpression expression = new MultiExpression(Enum.valueOf(SetLogic.class,
getSelectedExpression().getMultiSetLogic().name()),
getSelectedExpression().getPUIs().split(MultiRuleExpression.parameterDelimiter, 0),
getSelectedExpression().getSinglePui(), getSelectedExpression().getOperator(),
getSelectedExpression().getVal().toString(), getSelectedExpression().getDisplay());
String ruleResult = expression.execute(valuesMap);
if (ruleResult != null) {
controlPanel.setRuleResultField(ruleResult);
} else {
controlPanel.setRuleResultField("");
}
}
}
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data,
long syncTime) {
updateFromFeed(data);
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return feedProvidersRef.get();
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiViewManifestation.java |
551 | expressionsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
controlPanel.loadRule();
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiViewManifestation.java |
552 | @SuppressWarnings("unchecked")
public class MultiRuleExpressionsTableModel extends AbstractTableModel {
private MultiRuleExpressionList eList = currentExpressions;
private List<String> numbers = new ArrayList<String>();
private List<String> rulesNames = new ArrayList<String>();
private List<String> displayedStrings = new ArrayList<String>();
private List<List<String>> lists = Arrays.asList(numbers, rulesNames, displayedStrings);
private final List<String> columnNames = new ArrayList<String>();
/**
* Initializes the expression model.
*/
MultiRuleExpressionsTableModel(){
columnNames.add(bundle.getString("NumberLabel"));
columnNames.add(bundle.getString("RuleName"));
columnNames.add(bundle.getString("DisplayedString"));
loadExpressions();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return eList.size();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex){
List<String> list = getListForColumn(columnIndex);
String value = list.get(rowIndex);
return columnIndex == 3 ? Double.valueOf(value) : value;
}
private List<String> getListForColumn(int col){
return lists.get(col);
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col==1 && value != null){
eList.getExp(row).setName(value.toString());
}
if (col==2 && value != null){
eList.getExp(row).setDisplay(value.toString());
}
multiComponent.getData().setCode(eList.toString());
fireTableCellUpdated(row, col);
fireFocusPersist();
}
private void loadExpressions(){
MultiRuleExpression e;
for (int i = 0; i < eList.size(); i++){
e = eList.getExp(i);
numbers.add(Integer.valueOf(i+1).toString());
rulesNames.add(e.getName());
displayedStrings.add(e.getDisplay());
}
}
/**
* Clears the model.
*/
public void clearModel() {
numbers.clear();
rulesNames.clear();
displayedStrings.clear();
loadExpressions();
fireTableDataChanged();
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiViewManifestation.java |
553 | @SuppressWarnings("unchecked")
class TelemetryModel extends AbstractTableModel{
private List<String> pui = new ArrayList<String>();
private List<String> baseDisplay = new ArrayList<String>();
private List<String> currentValues = new ArrayList<String>();
private List<List<String>> lists = Arrays.asList(pui, baseDisplay, currentValues);
private final List<String> columnNames = new ArrayList<String>();
/**
* Initializes the telemetry model.
*/
TelemetryModel(){
columnNames.add(bundle.getString("PuiLabel"));
columnNames.add(bundle.getString("BaseDisplayLabel"));
columnNames.add(bundle.getString("currentValueLabel"));
loadTelemetry();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return telemetryElements.size();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex){
List<String> list = getListForColumn(columnIndex);
if (list.size() == 0) {
return "";
}
return list.get(rowIndex);
}
private List<String> getListForColumn(int col){
return lists.get(col);
}
/**
* Loads the telemetry.
*/
protected void loadTelemetry(){
refreshTelemetry();
for (AbstractComponent ac : telemetryElements){
pui.add(ac.getExternalKey());
baseDisplay.add(ac.getDisplayName());
currentValues.add("");
}
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col==2 && value != null) {
currentValues.set(row, value.toString());
}
fireTableCellUpdated(row, col);
}
/**
* Clears the telemetry model.
*/
public void clearModel() {
pui.clear();
baseDisplay.clear();
currentValues.clear();
loadTelemetry();
controlPanel.updatePassThroughControl();
fireTableDataChanged();
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_expressions_MultiViewManifestation.java |
554 | public interface EvaluatorProvider {
/**
* Returns the language type of {@link #getCode()}. This should be unique but the burden is on the
* evaluation creator to ensure evaluation providers can be discovered.
* @return the string representing the language
*/
String getLanguage();
/**
* Takes the code to execute and verifies its correctness.
* @param code to execute
* @return executor that can evaluate the given code.
*/
Executor compile(String code); // this will eventually throw an exception to allow verification of code
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_spi_EvaluatorProvider.java |
555 | public interface MultiProvider {
/**
* Returns the language type of {@link #getCode()}. This should be unique but the burden is on the
* evaluation creator to ensure evaluation providers can be discovered.
* @return the string representing the language
*/
String getLanguage();
/**
* Takes the code to execute and verifies its correctness.
* @param code to execute
* @return executor that can evaluate the given code.
*/
Executor compile(String code); // this will eventually throw an exception to allow verification of code
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_spi_MultiProvider.java |
556 | public class EnumeratorViewPolicy implements Policy {
private static boolean isEnumerator(AbstractComponent component) {
Evaluator ev = component.getCapability(Evaluator.class);
return ev != null && EnumEvaluator.LANGUAGE_STRING.equals(ev.getLanguage());
}
@Override
public ExecutionResult execute(PolicyContext context) {
boolean result = true;
ViewInfo viewInfo = context.getProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), ViewInfo.class);
if (viewInfo.getViewClass().equals(ExpressionsViewManifestation.class)) {
AbstractComponent targetComponent = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class);
result = isEnumerator(targetComponent);
}
String message = null;
if (!result) {
message = "Expression View only valid for enumerators";
}
return new ExecutionResult(context, result, message);
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_EnumeratorViewPolicy.java |
557 | public class EvaluatorComponentPreferredViewPolicy implements Policy {
private static final List<String> COMPONENTS_WITH_PREFERRED_VIEW = Arrays
.asList(EvaluatorComponent.class.getName());
@Override
public ExecutionResult execute(PolicyContext context) {
ExecutionResult er = new ExecutionResult(context, true, "");
ViewType viewType = context.getProperty(PolicyContext.PropertyName.VIEW_TYPE.getName(),ViewType.class);
// return false if the specified view should be the preferred view
boolean isInspectionView =
ViewType.OBJECT.equals(viewType)
|| ViewType.CENTER.equals(viewType);
er.setStatus(!(isInspectionView && isDefaultView(context, viewType) && componentHasDefault(context)));
return er;
}
private boolean isDefaultView(PolicyContext context, ViewType viewType) {
ViewInfo vr = context.getProperty(
PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(),
ViewInfo.class);
return (ViewType.OBJECT.equals(viewType) && InfoViewManifestation.class.equals(vr.getViewClass()));
}
private boolean componentHasDefault(PolicyContext context) {
AbstractComponent ac = context.getProperty(
PolicyContext.PropertyName.TARGET_COMPONENT.getName(),
AbstractComponent.class);
return COMPONENTS_WITH_PREFERRED_VIEW.contains(ac.getClass().getName());
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_EvaluatorComponentPreferredViewPolicy.java |
558 | public class EvaluatorViewPolicy implements Policy {
private boolean hasFeedProvider(AbstractComponent component) {
return component.getCapability(FeedProvider.class) != null && !component.getClass().equals(EvaluatorComponent.class);
}
@Override
public ExecutionResult execute(PolicyContext context) {
boolean result = true;
ViewInfo viewInfo = context.getProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), ViewInfo.class);
if (InfoViewManifestation.class.equals(viewInfo.getViewClass())) {
AbstractComponent targetComponent = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class);
result = hasFeedProvider(targetComponent);
}
String message = null;
if (!result) {
message = "Evaluator View only valid for components with evalutors";
}
return new ExecutionResult(context, result, message);
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_EvaluatorViewPolicy.java |
559 | public class InfoViewManifestation extends FeedView {
private static final long serialVersionUID = 1L;
private static final ResourceBundle bundle = ResourceBundle.getBundle("Bundle");
public static final String VIEW_NAME = bundle.getString("InfoViewRoleName");
public ValueModel tableModel;
private int valueType = 1;
private JLabel valueLabel = new JLabel();
private JTextField inputTestValue = new JTextField();
private FeedProvider feed;
private String f;
private JRadioButton alphaValue;
private JRadioButton testValue;
private Border componentBorder = null;
public InfoViewManifestation(AbstractComponent component, ViewInfo info) {
super(component, info);
feed = component.getCapability(FeedProvider.class);
f = feed.getSubscriptionId();
if (getColor("border") != null) {
componentBorder = BorderFactory.createLineBorder(getColor("border"));
inputTestValue.setBorder(componentBorder);
}
buildGUI();
}
private Color getColor(String name) {
return UIManager.getColor(name);
}
@Override
public List<FeedProvider> getVisibleFeedProviders() {
// if this is identified as a performance hotspot, then cache this list and recreate when
// children are added or deleted
List<AbstractComponent> components = getManifestedComponent().getComponents();
List<FeedProvider> providers = new ArrayList<FeedProvider>(components.size() + 1);
FeedProvider fp = getFeedProvider(getManifestedComponent());
if (fp != null) {
providers.add(fp);
}
for (AbstractComponent component : components) {
fp = getFeedProvider(component);
if (fp != null) {
providers.add(fp);
}
}
return providers;
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data,
long syncTime) {
updateFromFeed(data);
}
@Override
public void updateFromFeed(Map<String, List<Map<String, String>>> data) {
if (!data.isEmpty()) {
tableModel.updateFromFeed(data);
}
//Provide alpha value for radio button
List<Map<String,String>> feedDataForThisComponentCastAsMap = data.get(f);
if (feedDataForThisComponentCastAsMap == null || feedDataForThisComponentCastAsMap.isEmpty()) {
return;
}
Map<String, String> entry = feedDataForThisComponentCastAsMap.get( feedDataForThisComponentCastAsMap.size() -1 );
RenderingInfo ri = feed.getRenderingInfo(entry);
valueLabel.setText(ri.getValueText());
valueLabel.setForeground(ri.getValueColor());
if (!valueLabel.isVisible()) valueLabel.setVisible(true);
}
@Override
public void updateMonitoredGUI() {
tableModel.clearModel();
}
private void buildGUI() {
// show the language, code, the table, and the evaluated value
setLayout(new GridBagLayout());
//Buttons to choose alpha and test values
alphaValue = new JRadioButton();
alphaValue.setText("Alpha Value: ");
alphaValue.setActionCommand("1");
alphaValue.setSelected(true);
testValue = new JRadioButton();
testValue.setText("Test Value: ");
testValue.setActionCommand("2");
ButtonGroup selectValue = new ButtonGroup();
selectValue.add(alphaValue);
selectValue.add(testValue);
alphaValue.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
valueType = 1;
}
});
testValue.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
valueType = 2;
}
});
//Input field for test value
inputTestValue.getAccessibleContext().setAccessibleName(testValue.getText());
inputTestValue.setEditable(true);
inputTestValue.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent arg0) {
valueType = 2;
testValue.setSelected(true);
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
//Table of evaluators associated with given component
JTable valueTable = new JTable(tableModel = new ValueModel()) {
private static final long serialVersionUID = 1L;
@Override
public String getToolTipText(MouseEvent event) {
String tip = null;
java.awt.Point p = event.getPoint();
int colIndex = columnAtPoint(p);
int realColumnIndex = convertColumnIndexToModel(colIndex);
if (realColumnIndex == 2) {
tip = bundle.getString("ValuesToolTip");
}
return tip;
}
};
valueTable.setAutoCreateColumnsFromModel(true);
valueTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
valueTable.setRowSelectionAllowed(false);
JScrollPane tableScrollPane = new JScrollPane(valueTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
if (componentBorder != null) {
tableScrollPane.setBorder(componentBorder);
}
//add buttons to panel
GridBagConstraints alphaConstraints = getConstraints(0,0);
alphaConstraints.gridwidth = 1;
alphaConstraints.insets = new Insets(3,5,2,5);
alphaConstraints.weighty = 0;
alphaConstraints.fill = GridBagConstraints.NONE;
alphaConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
add(alphaValue, alphaConstraints);
GridBagConstraints valueConstraints = getConstraints(1,0);
valueConstraints.gridwidth = 1;
valueConstraints.insets = new Insets(6,5,2,5);
valueConstraints.weighty = 0;
valueConstraints.fill = GridBagConstraints.HORIZONTAL;
valueConstraints.fill = GridBagConstraints.LAST_LINE_START;
add(valueLabel, valueConstraints);
GridBagConstraints testConstraints = getConstraints(0,1);
testConstraints.gridwidth = 1;
testConstraints.insets = new Insets(0,5,5,5);
testConstraints.weighty = 0;
testConstraints.fill = GridBagConstraints.NONE;
testConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
add(testValue, testConstraints);
GridBagConstraints inputConstraints = getConstraints(1,1);
inputConstraints.gridwidth = 1;
inputConstraints.insets = new Insets(0,5,5,5);
inputConstraints.weighty = 0;
inputConstraints.fill = GridBagConstraints.HORIZONTAL;
inputConstraints.anchor = GridBagConstraints.LINE_START;
add(inputTestValue, inputConstraints);
//add evaluators table to panel
GridBagConstraints tableConstraints = getConstraints(0,2);
tableConstraints.gridwidth = 2;
tableConstraints.insets = new Insets(0,5,3,5);
tableConstraints.weighty = 1;
tableConstraints.weightx = 1;
tableConstraints.fill = GridBagConstraints.BOTH;
add(tableScrollPane, tableConstraints);
}
private GridBagConstraints getConstraints(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = x == 0 ? 0 : 1;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(y%2==0?5:0, 5, 0, x==1?5:0);
if (x == 0) {
gbc.fill = GridBagConstraints.NONE;
}
gbc.anchor = GridBagConstraints.NORTHWEST;
return gbc;
}
protected ArrayList<Evaluator> getEvaluatorList(){
ArrayList<Evaluator> eList = new ArrayList<Evaluator>();
//Check for imars enumerators
Evaluator imars = getManifestedComponent().getCapability(Evaluator.class);
if (imars != null){
eList.add(imars);
}
//Check for user created enumerators
Collection<AbstractComponent> parents = getManifestedComponent().getReferencingComponents();
for (AbstractComponent p : parents){
Evaluator e = p.getCapability(Evaluator.class);
if (e!= null && p.getClass().equals(EvaluatorComponent.class)) {
eList.add(e);
}
}
return eList;
}
// the data structures could be optimized in this model (perhaps using a Map instead of parallel lists),
// but since this is not expected to be used
// heavily a simple implementation was used
class ValueModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private List<String> displayValues = new ArrayList<String>();
private List<String> code = new ArrayList<String>();
private List<String> name = new ArrayList<String>();
@SuppressWarnings("unchecked")
private List<List<String>> lists = Arrays.asList(name,code, displayValues);
private static final int FEED_VALUE_COLUMN = 2;
public ArrayList<Evaluator> eList = getEvaluatorList();
private final List<String> columnNames = new ArrayList<String>();
ValueModel() {
columnNames.add(bundle.getString("EvaluatorNameLabel"));
columnNames.add(bundle.getString("ExpressionsLabel"));
columnNames.add(bundle.getString("ResultValueLabel"));
loadFeeds();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return eList.size();
//return getVisibleFeedProviders().size();
}
public void updateFromFeed(Map<String, List<Map<String, String>>> data) {
if (!eList.isEmpty()) {
// update the live values from the feed values
String value = "";
List<Map<String, String>> values = data.get(f);
if (values != null && !values.isEmpty()) {
value = values.get(values.size()-1).get(FeedProvider.NORMALIZED_VALUE_KEY);
}
for (int i = 0; i < eList.size(); i++){
String lastValue = displayValues.set(i, value);
if (!value.equals(lastValue)) {
fireTableCellUpdated(i, FEED_VALUE_COLUMN);
}
}
updateOutput(data);
}
}
private void updateOutput(Map<String, List<Map<String, String>>> originalData) {
Map<String, List<Map<String, String>>> data = new HashMap<String, List<Map<String,String>>>();
String val = "";
if (valueType == 1) {
val = displayValues.get(0);
}
if (valueType == 2) {
val = inputTestValue.getText();
}
Evaluator e;
for (int i = 0; i < eList.size(); i++){
e = eList.get(i);
Map<String,String> values = new HashMap<String,String>();
List<Map<String,String>> origValues = originalData.get(f);
if (origValues != null && !origValues.isEmpty()) {
values.putAll(origValues.get(origValues.size()-1));
values.put(FeedProvider.NORMALIZED_VALUE_KEY, val);
RenderingInfo originalInfo = RenderingInfo.valueOf(values.get(FeedProvider.NORMALIZED_RENDERING_INFO));
RenderingInfo ri = new RenderingInfo(
val,
originalInfo.getValueColor(),
originalInfo.getStatusText(),
originalInfo.getStatusColor(),
true
);
values.put(FeedProvider.NORMALIZED_RENDERING_INFO, ri.toString());
data.put(f, Collections.singletonList(values));
}
if (e != null) {
RenderingInfo ri = e.evaluate(data, getVisibleFeedProviders());
setValueAt(ri == null ? "" : ri.getValueText(), i, FEED_VALUE_COLUMN);
} else {
setValueAt("No executor found", i, FEED_VALUE_COLUMN);
}
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
private void loadFeeds() {
Evaluator e;
for (int i = 0; i < eList.size(); i++){
e = eList.get(i);
name.add(e.getDisplayName());
displayValues.add(null);
code.add(e.getCode());
}
}
public void clearModel() {
displayValues.clear();
code.clear();
name.clear();
loadFeeds();
fireTableDataChanged();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
List<String> list = getListForColumn(columnIndex);
return list.get(rowIndex);
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
assert columnIndex == FEED_VALUE_COLUMN : "only result column should be editable";
displayValues.set(rowIndex, aValue.toString());
}
private List<String> getListForColumn(int col) {
return lists.get(col);
}
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_InfoViewManifestation.java |
560 | alphaValue.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
valueType = 1;
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_InfoViewManifestation.java |
561 | testValue.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
valueType = 2;
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_InfoViewManifestation.java |
562 | inputTestValue.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent arg0) {
valueType = 2;
testValue.setSelected(true);
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}); | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_InfoViewManifestation.java |
563 | JTable valueTable = new JTable(tableModel = new ValueModel()) {
private static final long serialVersionUID = 1L;
@Override
public String getToolTipText(MouseEvent event) {
String tip = null;
java.awt.Point p = event.getPoint();
int colIndex = columnAtPoint(p);
int realColumnIndex = convertColumnIndexToModel(colIndex);
if (realColumnIndex == 2) {
tip = bundle.getString("ValuesToolTip");
}
return tip;
}
}; | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_InfoViewManifestation.java |
564 | class ValueModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private List<String> displayValues = new ArrayList<String>();
private List<String> code = new ArrayList<String>();
private List<String> name = new ArrayList<String>();
@SuppressWarnings("unchecked")
private List<List<String>> lists = Arrays.asList(name,code, displayValues);
private static final int FEED_VALUE_COLUMN = 2;
public ArrayList<Evaluator> eList = getEvaluatorList();
private final List<String> columnNames = new ArrayList<String>();
ValueModel() {
columnNames.add(bundle.getString("EvaluatorNameLabel"));
columnNames.add(bundle.getString("ExpressionsLabel"));
columnNames.add(bundle.getString("ResultValueLabel"));
loadFeeds();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public int getRowCount() {
return eList.size();
//return getVisibleFeedProviders().size();
}
public void updateFromFeed(Map<String, List<Map<String, String>>> data) {
if (!eList.isEmpty()) {
// update the live values from the feed values
String value = "";
List<Map<String, String>> values = data.get(f);
if (values != null && !values.isEmpty()) {
value = values.get(values.size()-1).get(FeedProvider.NORMALIZED_VALUE_KEY);
}
for (int i = 0; i < eList.size(); i++){
String lastValue = displayValues.set(i, value);
if (!value.equals(lastValue)) {
fireTableCellUpdated(i, FEED_VALUE_COLUMN);
}
}
updateOutput(data);
}
}
private void updateOutput(Map<String, List<Map<String, String>>> originalData) {
Map<String, List<Map<String, String>>> data = new HashMap<String, List<Map<String,String>>>();
String val = "";
if (valueType == 1) {
val = displayValues.get(0);
}
if (valueType == 2) {
val = inputTestValue.getText();
}
Evaluator e;
for (int i = 0; i < eList.size(); i++){
e = eList.get(i);
Map<String,String> values = new HashMap<String,String>();
List<Map<String,String>> origValues = originalData.get(f);
if (origValues != null && !origValues.isEmpty()) {
values.putAll(origValues.get(origValues.size()-1));
values.put(FeedProvider.NORMALIZED_VALUE_KEY, val);
RenderingInfo originalInfo = RenderingInfo.valueOf(values.get(FeedProvider.NORMALIZED_RENDERING_INFO));
RenderingInfo ri = new RenderingInfo(
val,
originalInfo.getValueColor(),
originalInfo.getStatusText(),
originalInfo.getStatusColor(),
true
);
values.put(FeedProvider.NORMALIZED_RENDERING_INFO, ri.toString());
data.put(f, Collections.singletonList(values));
}
if (e != null) {
RenderingInfo ri = e.evaluate(data, getVisibleFeedProviders());
setValueAt(ri == null ? "" : ri.getValueText(), i, FEED_VALUE_COLUMN);
} else {
setValueAt("No executor found", i, FEED_VALUE_COLUMN);
}
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
private void loadFeeds() {
Evaluator e;
for (int i = 0; i < eList.size(); i++){
e = eList.get(i);
name.add(e.getDisplayName());
displayValues.add(null);
code.add(e.getCode());
}
}
public void clearModel() {
displayValues.clear();
code.clear();
name.clear();
loadFeeds();
fireTableDataChanged();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
List<String> list = getListForColumn(columnIndex);
return list.get(rowIndex);
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
assert columnIndex == FEED_VALUE_COLUMN : "only result column should be editable";
displayValues.set(rowIndex, aValue.toString());
}
private List<String> getListForColumn(int col) {
return lists.get(col);
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_InfoViewManifestation.java |
565 | public class MultiChildRemovalPolicy implements Policy {
/* (non-Javadoc)
* @see gov.nasa.arc.mct.policy.Policy#execute(gov.nasa.arc.mct.policy.PolicyContext)
*/
@Override
public ExecutionResult execute(PolicyContext context) {
AbstractComponent multi = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class);
@SuppressWarnings("unchecked")
Collection<AbstractComponent> sources = context.getProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(), Collection.class);
boolean canExecute = true;
if (multi.getCapability(MultiComponent.class) != null) {
for (AbstractComponent ac : sources) {
if (ac.getExternalKey() != null) {
if (((MultiComponent) multi).getData().getCode().contains(ac.getExternalKey())) {
canExecute = false;
}
}
}
}
if (canExecute) {
return new ExecutionResult(context, true, "");
} else {
return new ExecutionResult(context, false, "One or more objects could not be removed because it is being used");
}
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_MultiChildRemovalPolicy.java |
566 | public class MultiCompositionPolicy implements Policy {
/* (non-Javadoc)
* @see gov.nasa.arc.mct.policy.Policy#execute(gov.nasa.arc.mct.policy.PolicyContext)
*/
@Override
public ExecutionResult execute(PolicyContext context) {
AbstractComponent multi = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), AbstractComponent.class);
@SuppressWarnings("unchecked")
Collection<AbstractComponent> sources = context.getProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(), Collection.class);
if (multi.getCapability(MultiComponent.class) != null) {
if (sources != null) {
for (AbstractComponent ac : sources) {
if (ac.getCapability(FeedProvider.class) == null) {
OptionBox.showMessageDialog(
null,
"Only objects that provide data can be added\nto a new multi",
"Error",
OptionBox.ERROR_MESSAGE);
return new ExecutionResult(context, false, "");
}
}
}
}
return new ExecutionResult(context, true, "");
}
} | false | evaluatorComponent_src_main_java_gov_nasa_arc_mct_evaluator_view_MultiCompositionPolicy.java |
567 | public class TestInfoViewManifestation extends BaseUITest {
@Mock
private EvaluatorComponent parentComponent;
@Mock
private AbstractComponent childComponent;
@Mock
private EvaluatorData mockData;
private ArrayList<Evaluator> eList;
@Mock
private FeedProvider provider;
@Mock
private EvaluatorProvider evaluatorProvider;
private static final String feedId = "feed";
private static class ReturnExecutor implements Executor {
@Override
public FeedProvider.RenderingInfo evaluate(Map<String, List<Map<String, String>>> data, List<FeedProvider> feedProviders) {
List<Map<String, String>> l = data.get(feedId);
String value = l.get(l.size()-1).get(FeedProvider.NORMALIZED_VALUE_KEY);
return new FeedProvider.RenderingInfo(value, Color.green, "", Color.black, true);
}
public boolean requiresMultipleInputs() {
return false;
}
}
@BeforeMethod
public void setup() {
final String language = "mskEnum";
MockitoAnnotations.initMocks(this);
List<AbstractComponent> feedProviders = Collections.<AbstractComponent>singletonList(childComponent);
Mockito.when(childComponent.getCapability(FeedProvider.class)).thenReturn(provider);
Mockito.when(parentComponent.getCapability(FeedProvider.class)).thenReturn(provider);
Mockito.when(parentComponent.getComponents()).thenReturn(feedProviders);
Mockito.when(parentComponent.getData()).thenReturn(mockData);
Mockito.when(provider.getSubscriptionId()).thenReturn(feedId);
Mockito.when(evaluatorProvider.getLanguage()).thenReturn(language);
Mockito.when(mockData.getLanguage()).thenReturn(language);
Mockito.when(evaluatorProvider.compile(Mockito.anyString())).thenReturn(new ReturnExecutor());
new EvaluatorProviderRegistry().addProvider(evaluatorProvider);
final Executor executor =
EvaluatorProviderRegistry.getExecutor(EvaluatorComponent.class.cast(parentComponent));
final Evaluator e = new Evaluator() {
@Override
public String getCode() {
return "test";
}
@Override
public String getDisplayName() {
return "testName";
}
@Override
public String getLanguage() {
return language;
}
public boolean requiresMultipleInputs() {
return false;
}
@Override
public FeedProvider.RenderingInfo evaluate(Map<String, List<Map<String, String>>> data,
List<FeedProvider> providers) {
return executor.evaluate(data, providers);
}
};
final Evaluator e2 = new Evaluator() {
@Override
public String getCode() {
return "test2";
}
@Override
public String getDisplayName() {
return "testName2";
}
@Override
public String getLanguage() {
return language;
}
public boolean requiresMultipleInputs() {
return false;
}
@Override
public FeedProvider.RenderingInfo evaluate(Map<String, List<Map<String, String>>> data,
List<FeedProvider> providers) {
return executor.evaluate(data, providers);
}
};
eList = new ArrayList<Evaluator>();
eList.add(e);
eList.add(e2);
}
@AfterMethod
public void cleanup() {
new EvaluatorProviderRegistry().removeProvider(evaluatorProvider);
}
@SuppressWarnings("unchecked")
@Test
public void testInfoView() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
InfoViewManifestation manifestation = new InfoViewManifestation(parentComponent, new ViewInfo(InfoViewManifestation.class,"info", ViewType.OBJECT));
for (AncestorListener listener : manifestation.getAncestorListeners()) {
listener.ancestorRemoved(null);
manifestation.removeAncestorListener(listener);
}
FrameFixture fixture = showInFrame(manifestation, "test");
JTableFixture tableFixture = fixture.table();
FeedProvider.RenderingInfo ri = new FeedProvider.RenderingInfo(
"1",
Color.gray,
"a",
Color.gray,
true
);
Mockito.when(provider.getRenderingInfo(Mockito.anyMap())).thenReturn(ri);
Map<String, String> dataInfo = new HashMap<String,String>();
dataInfo.put(FeedProvider.NORMALIZED_VALUE_KEY, "1");
dataInfo.put(FeedProvider.NORMALIZED_RENDERING_INFO, ri.toString());
Map<String, List<Map<String, String>>> data =
Collections.singletonMap(provider.getSubscriptionId(),
Collections.singletonList(dataInfo));
Field f1 = InfoViewManifestation.class.getField("tableModel");
f1.setAccessible(true);
Object view = f1.get(manifestation);
Field f2 = ValueModel.class.getField("eList");
f2.setAccessible(true);
f2.set(view, eList);
((ValueModel)view).clearModel();
manifestation.updateFromFeed(data);
JLabelFixture labelFixture = new Query().labelIn(fixture);
labelFixture.requireText("1");
JRadioButtonFixture buttonA = new Query().accessibleNameMatches("Alpha Value: ").radioButtonIn(fixture);
buttonA.check();
manifestation.updateFromFeed(data);
JTableCellFixture cell = tableFixture.cell(row(0).column(2));
JTableCellFixture cell2 = tableFixture.cell(row(1).column(2));
cell.requireValue("1");
cell2.requireValue("1");
buttonA.uncheck();
JRadioButtonFixture buttonI = new Query().accessibleNameMatches("Test Value: ").radioButtonIn(fixture);
buttonI.check();
JTextComponentFixture textFixture = new Query().textBoxIn(fixture);
textFixture.enterText("2");
manifestation.updateFromFeed(data);
cell.requireValue("2");
cell2.requireValue("2");
}
} | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_view_TestInfoViewManifestation.java |
568 | final Evaluator e = new Evaluator() {
@Override
public String getCode() {
return "test";
}
@Override
public String getDisplayName() {
return "testName";
}
@Override
public String getLanguage() {
return language;
}
public boolean requiresMultipleInputs() {
return false;
}
@Override
public FeedProvider.RenderingInfo evaluate(Map<String, List<Map<String, String>>> data,
List<FeedProvider> providers) {
return executor.evaluate(data, providers);
}
}; | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_view_TestInfoViewManifestation.java |
569 | final Evaluator e2 = new Evaluator() {
@Override
public String getCode() {
return "test2";
}
@Override
public String getDisplayName() {
return "testName2";
}
@Override
public String getLanguage() {
return language;
}
public boolean requiresMultipleInputs() {
return false;
}
@Override
public FeedProvider.RenderingInfo evaluate(Map<String, List<Map<String, String>>> data,
List<FeedProvider> providers) {
return executor.evaluate(data, providers);
}
}; | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_view_TestInfoViewManifestation.java |
570 | private static class ReturnExecutor implements Executor {
@Override
public FeedProvider.RenderingInfo evaluate(Map<String, List<Map<String, String>>> data, List<FeedProvider> feedProviders) {
List<Map<String, String>> l = data.get(feedId);
String value = l.get(l.size()-1).get(FeedProvider.NORMALIZED_VALUE_KEY);
return new FeedProvider.RenderingInfo(value, Color.green, "", Color.black, true);
}
public boolean requiresMultipleInputs() {
return false;
}
} | false | evaluatorComponent_src_test_java_gov_nasa_arc_mct_evaluator_view_TestInfoViewManifestation.java |
571 | public interface EventProvider {
/**
* This represents the prefix used for subscriptions. The subscription id follows this
* string and can be used to actually do the subscription.
*/
public static final String TELEMETRY_TOPIC_PREFIX = "gov/nasa/arc/telemetry/id/";
/**
* Attempt to subscribe to events on the given topic. Return an
* indication of whether the subscription succeeded.
*
* @param topics to subscribe to
* @return topics subscribed to
*/
Collection<String> subscribeTopics(String... topic);
/**
* Stop subscribing to events on the given topic.
*
* @param topic the topic no longer being subscribed to
*/
void unsubscribeTopics(String... topic);
/**
* Refresh the subscription.
*/
public void refresh();
} | false | subscriptionManager_src_main_java_gov_nasa_arc_mct_event_services_EventProvider.java |
572 | public interface EventSubscriber extends EventHandler {
} | false | subscriptionManager_src_main_java_gov_nasa_arc_mct_event_services_EventSubscriber.java |
573 | public abstract class SubscriptionConstants {
/** An event property indicating that the event designates subscription status. */
public static final String SUBSCRIPTION_STATUS = "STATUS";
/**
* A value for the <code>SUBSCRIPTION_STATUS</code> property that indicates
* that the topic has been successfully subscribed-to.
*/
public static final String STATUS_SUBSCRIBED = "Subscribed";
/**
* A value for the <code>SUBSCRIPTION_STATUS</code> property that indicates
* that no provider for the topic was found.
*/
public static final String STATUS_UNAVAILABLE = "Unavailable";
} | false | subscriptionManager_src_main_java_gov_nasa_arc_mct_event_services_SubscriptionConstants.java |
574 | public class DefaultExceptionHandler implements UncaughtExceptionHandler {
private MCTLogger logger = MCTLogger.getLogger(DefaultExceptionHandler.class);
private static final MCTLogger ADVISORY_SERVICE_LOGGER = MCTLogger.getLogger("gov.nasa.jsc.advisory.service");
private final boolean enableDialogs;
/**
* Instantiates a handler to report MCT exceptions
*/
public DefaultExceptionHandler() {
this(true);
}
/**
* Instantiates a handler to report MCT exceptions.
* Allows disabling GUI elements, useful for unit testing.
*
* @param enableDialogs whether GUI dialogs should be also displayed.
*/
public DefaultExceptionHandler(boolean enableDialogs) {
this.enableDialogs = enableDialogs;
logger.debug("Started the default exception handler.");
}
/**
* Dispatches to class specific handlers that add specialized information.
* Method invoked when the given thread terminates due to the given uncaught exception.
*
* @param thread the thread
* @param t the exception
*/
@Override
public void uncaughtException(Thread thread, Throwable t) {
String str;
if (t.getCause() != null) {
str = t.getMessage() + " Caused by: "+ t.getCause().getMessage();
} else {
str = t.getMessage();
}
ADVISORY_SERVICE_LOGGER.error("MCT has detected an exception: " + str);
try {
throw t;
} catch (Throwable e) {
if (enableDialogs) {
generalizedHandler(e);
} else {
logger.error("MCT has detected an exception: ", e);
}
}
}
/**
* Default reporter.
*
* @param throwable the throwable
*/
private void generalizedHandler(Throwable throwable) {
String str;
if (throwable.getCause() != null) {
str = throwable.getMessage() + "\nCaused by: "+ throwable.getCause().getMessage();
} else {
str = throwable.getMessage();
}
logger.error(str, throwable);
if (enableDialogs) {
OptionBox.showMessageDialog(
null,
str + "\n"
+ "\n"
+ "See MCT log for more information.",
"Fatal Startup Error",
OptionBox.ERROR_MESSAGE
);
}
}
} | false | platform_src_main_java_gov_nasa_arc_mct_exception_DefaultExceptionHandler.java |
575 | public class DefaultExceptionHandlerTest {
protected static class MyAppender extends NullAppender {
List<LoggingEvent> events = new ArrayList<LoggingEvent>();
@Override
protected void append(LoggingEvent event) {
events.add(event);
}
@Override
public void doAppend(LoggingEvent event) {
append(event);
}
public void clearEvents() {
events.clear();
}
public List<LoggingEvent> getEvents() {
return events;
}
}
// Then, configure the underlying logger the way we want.
Logger logger = Logger.getLogger(DefaultExceptionHandler.class);
MyAppender appender = new MyAppender();
@BeforeClass
public void initLogging() {
logger.addAppender(appender);
}
@BeforeMethod
public void initTest() {
appender.clearEvents();
}
@AfterMethod
public void cleanTest() {
appender.clearEvents();
}
@Test
public void testInstantiation() throws Exception {
DefaultExceptionHandler handler = new DefaultExceptionHandler(false);
assertEquals(appender.getEvents().size(), 1);
}
@Test
public void testExceptionHandler() throws Exception {
UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler(false));
Thread t = new Thread() {
public void run() {
throw new RuntimeException("Should be uncaught");
}
};
t.start();
t.join();
Thread.setDefaultUncaughtExceptionHandler(handler);
assertEquals(appender.getEvents().size(), 2);
}
} | false | platform_src_test_java_gov_nasa_arc_mct_exception_DefaultExceptionHandlerTest.java |
576 | Thread t = new Thread() {
public void run() {
throw new RuntimeException("Should be uncaught");
}
}; | false | platform_src_test_java_gov_nasa_arc_mct_exception_DefaultExceptionHandlerTest.java |
577 | protected static class MyAppender extends NullAppender {
List<LoggingEvent> events = new ArrayList<LoggingEvent>();
@Override
protected void append(LoggingEvent event) {
events.add(event);
}
@Override
public void doAppend(LoggingEvent event) {
append(event);
}
public void clearEvents() {
events.clear();
}
public List<LoggingEvent> getEvents() {
return events;
}
} | false | platform_src_test_java_gov_nasa_arc_mct_exception_DefaultExceptionHandlerTest.java |
578 | public class PlotViewProvider extends AbstractComponentProvider {
final Collection<PolicyInfo> policyInfos;
private final List<ViewInfo> viewInfos;
public PlotViewProvider() {
policyInfos = Arrays.asList(new PolicyInfo(PolicyInfo.CategoryType.FILTER_VIEW_ROLE.getKey(), PlotViewPolicy.class),
new PolicyInfo(PolicyInfo.CategoryType.FILTER_VIEW_ROLE.getKey(), PlotStringPolicy.class)
);
viewInfos = Arrays.asList(
new ViewInfo(PlotViewManifestation.class, PlotViewManifestation.VIEW_ROLE_NAME, "gov.nasa.arc.mct.fastplot.view.PlotViewRole", ViewType.OBJECT),
new ViewInfo(PlotViewManifestation.class, PlotViewManifestation.VIEW_ROLE_NAME, "gov.nasa.arc.mct.fastplot.view.PlotViewRole", ViewType.CENTER),
new ViewInfo(PlotViewManifestation.class, PlotViewManifestation.VIEW_ROLE_NAME, "gov.nasa.arc.mct.fastplot.view.PlotViewRole", ViewType.EMBEDDED,
new ImageIcon(getClass().getResource("/images/plotViewButton-OFF.png")),
new ImageIcon(getClass().getResource("/images/plotViewButton-ON.png"))));
}
@Override
public Collection<ViewInfo> getViews(String componentTypeId) {
return viewInfos;
}
@Override
public Collection<PolicyInfo> getPolicyInfos() {
return policyInfos;
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_PlotViewProvider.java |
579 | public class TestPlotViewProvider {
private PlotViewProvider provider;
@BeforeMethod
public void setup() {
provider = new PlotViewProvider();
}
@Test
public void testGetters() {
Assert.assertEquals(provider.getComponentTypes(), Collections.emptyList());
Assert.assertEquals(provider.getMenuItemInfos(), Collections.emptyList());
}
@Test
public void testGetViewRoles() {
Assert.assertTrue(provider.getViews("").contains(new ViewInfo(PlotViewManifestation.class,"","gov.nasa.arc.mct.fastplot.view.PlotViewRole", ViewType.CENTER)));
}
@Test
public void testGetPolicyInfos() {
Collection<PolicyInfo> infos = provider.getPolicyInfos();
Assert.assertEquals(infos.size(), 2);
}
} | false | fastPlotViews_src_test_java_gov_nasa_arc_mct_fastplot_TestPlotViewProvider.java |
580 | public final class PolicyManagerAccess {
private static AtomicReference<PolicyManager> manager = new AtomicReference<PolicyManager>();
public void setPolicyManager(PolicyManager policyManager) {
manager.set(policyManager);
}
public void unsetPolicyManager(PolicyManager pm) {
manager.set(null);
}
public static PolicyManager getPolicyManager() {
return manager.get();
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_access_PolicyManagerAccess.java |
581 | public class PolicyManagerAccessTest {
@Mock private PolicyManager policyManager;
PolicyManagerAccess access;
@BeforeMethod
public void init() {
MockitoAnnotations.initMocks(this);
access = new PolicyManagerAccess();
}
@Test
public void testGettersSetters() {
assertNull(PolicyManagerAccess.getPolicyManager());
access.setPolicyManager(policyManager);
assertSame(PolicyManagerAccess.getPolicyManager(), policyManager);
access.unsetPolicyManager(null);
assertNull(PolicyManagerAccess.getPolicyManager());
}
} | false | fastPlotViews_src_test_java_gov_nasa_arc_mct_fastplot_access_PolicyManagerAccessTest.java |
582 | public interface AbstractPlottingPackage extends PlotSubject {
/**
* Construct a plot
* @param theAxisOrientation the axis on which time appears
* @param theXAxisSetting the location of the max and minimum points on the x-axis
* @param theYAxisSetting the location of the max and minimum points on the y-axis
* @param theTimeAxisSubsequentSetting specify how the time axis behaves after it is initially setup
* @param theNonTimeAxisMinSubsequentSetting specify how the non time axis lower minimum point behaves after it is initially setup
* @param theNonTimeAxisMaxSubsequentSetting specify how the non time axis maximum point behaves after it is initially setup
* @param timeAxisFont the font of the time axis labels
* @param plotLineThickness the thickness of the plot lines
* @param plotBackgroundFrameColor color of the frame outside of the plot
* @param plotAreaBackgroundColor color of the background of the plot
* @param timeAxisIntercept the point at which the time axis intercepts the non time axis
* @param timeAxisColor color of the time axis
* @param timeAxisLabelColor color of the labels on the time axis
* @param nonTimeAxisLabelColor color of labels on the non-time axis
* @param timeAxisDataFormat format of the time axis labels
* @param nonTimeAxisColor color of the non time axis
* @param gridLineColor color of the grid lines
* @param minSamplesForAutoScale
* @param scrollRescaleTimeMargine padding percentage time axis
* @param scrollRescaleNonTimeMinMargine padding percentage non time axis min end
* @param scrollRescaleNonTimeMaxMargine padding percentage non time axis max end
* @param theNonTimeVaribleAxisMinValue initial minimum non time axis value
* @param theNonTimeVaribleAxisMaxValue initial maximum non time axis value
* @param theTimeVariableAxisMinValue initial minimum time axis value
* @param theTimeVariableAxisMaxValue initial maximum time axis value
* @param isCompressionEnabled true if plot should compress data to match the pixel resolution. False if it should not.
* @param isTimeLabelsEnabled true if time labels enabled; otherwise false.
* @param isLocalControlEnabled true if local control enabled; otherwise false.
* @param ordinalPositionInStackedPlot true if ordinal position in stacked plot; otherwise false.
* @param plotLineDraw indicates how to draw the plot (whether to include lines, markers, etc)
* @param plotLineConnectionType the method of connecting lines on the plot
* @param thePlotAbstraction plotAbstraction side of the bridge.
* @param thePlotLabelingAlgorithm the plot labeling abbreviation algorithm.
*/
public void createChart(AxisOrientationSetting theAxisOrientation,
XAxisMaximumLocationSetting theXAxisSetting,
YAxisMaximumLocationSetting theYAxisSetting,
TimeAxisSubsequentBoundsSetting theTimeAxisSubsequentSetting,
NonTimeAxisSubsequentBoundsSetting theNonTimeAxisMinSubsequentSetting,
NonTimeAxisSubsequentBoundsSetting theNonTimeAxisMaxSubsequentSetting,
Font timeAxisFont,
int plotLineThickness,
Color plotBackgroundFrameColor,
Color plotAreaBackgroundColor,
int timeAxisIntercept,
Color timeAxisColor,
Color timeAxisLabelColor,
Color nonTimeAxisLabelColor,
String timeAxisDataFormat,
Color nonTimeAxisColor,
Color gridLineColor,
int minSamplesForAutoScale,
double scrollRescaleTimeMargine,
double scrollRescaleNonTimeMinMargine,
double scrollRescaleNonTimeMaxMargine,
double theNonTimeVaribleAxisMinValue,
double theNonTimeVaribleAxisMaxValue,
long theTimeVariableAxisMinValue,
long theTimeVariableAxisMaxValue,
boolean isCompressionEnabled,
boolean isTimeLabelsEnabled,
boolean isLocalControlEnabled,
boolean ordinalPositionInStackedPlot,
PlotLineDrawingFlags plotLineDraw,
PlotLineConnectionType plotLineConnectionType,
PlotAbstraction thePlotAbstraction,
AbbreviatingPlotLabelingAlgorithm thePlotLabelingAlgorithm);
/**
* Get instance of the plot wrapped in a JFrame.
* @return the plot wrapped in a JFrame.
*/
public JComponent getPlotPanel();
/**
* Add a data set to the plot.
* @param dataSetName unique name of the data set.
* @param plottingColor desired plotting color of data set.
*/
public void addDataSet(String dataSetName, Color plottingColor);
/**
* Add a data set to the plot.
* @param lowerCase lowercase unique name of the data set.
* @param plottingColor desired plotting color of data set.
* @param displayName the display name.
*/
public void addDataSet(String lowerCase, Color plottingColor, String displayName);
/**
* Determine if data set is defined in plot.
* @param setName the dataset name.
* @return true if the dataset is defined in the plot, false otherwise.
*/
public boolean isKnownDataSet(String setName);
/**
* Update the legend entry for the corresponding data set.
* @param dataSetName name of the data set.
* @param info rendering information.
*/
public void updateLegend(String dataSetName, FeedProvider.RenderingInfo info);
/**
* Instruct the plot to redraw.
*/
public void refreshDisplay();
/**
* Return the number of data sets on the plot.
* @return the number of data sets.
*/
public int getDataSetSize();
/**
* Return the state of the alarm which indicates if plot has experienced data which is outside.
* of its current non time max axis limit.
* @return non-time max. limit alarm state.
*/
public LimitAlarmState getNonTimeMaxAlarmState();
/**
* Return the state of the alarm which indicates if plot has experienced data which is outside.
* of its current non time min axis limit.
* @return non-time min. limit alarm state.
*/
public LimitAlarmState getNonTimeMinAlarmState();
/**
* Return current time axis minimum as long.
* @return long current time axis minimal.
*/
public long getCurrentTimeAxisMinAsLong();
/**
* Return the current time axis minimum.
* @return Gregorian calendar for current time axis minimal.
*/
public GregorianCalendar getCurrentTimeAxisMin();
/**
* Return current time axis maximum.
* @return Gregorian calendar for current time axis maximum.
*/
public GregorianCalendar getCurrentTimeAxisMax();
/**
* Return current time axis maximum as long.
* @return long current time axis maximum.
*/
public long getCurrentTimeAxisMaxAsLong();
/**
* Return the current nonTime axis minimum.
* @return double current non-time axis minimal.
*/
public double getCurrentNonTimeAxisMin();
/**
* Return current nonTime axis maximum.
* @return double current non-time axis maximum.
*/
public double getCurrentNonTimeAxisMax();
/**
* Instruct the plot to show a time sync line.
* @param time at which to show the time sync line.
*/
public void showTimeSyncLine(GregorianCalendar time);
/**
* Instruct the plot to remove any time sync line currently being displayed.
*/
public void removeTimeSyncLine();
/**
* Return the time axis setting which indicates if time is on the x or y axis.
* @return axis orientation setting.
*/
public AxisOrientationSetting getAxisOrientationSetting();
/**
* Return the x-axis maximum location which indicates if the maximum is on the left or right end of this axis.
* @return X-axis maximum location setting.
*/
public XAxisMaximumLocationSetting getXAxisMaximumLocation();
/**
* Return the y-axis maximum location which indicates if the maximum is at the top or bottom of this axis.
* @return Y-axis maximum location setting.
*/
public YAxisMaximumLocationSetting getYAxisMaximumLocation();
/**
* Return the plot's mode when data exceeds the current span of the time axis.
* @return time axis subsequent bounds settings.
*/
public TimeAxisSubsequentBoundsSetting getTimeAxisSubsequentSetting();
/**
* Return the plot's mode when data exceeds the current minimum bound of the non time axis.
* @return non-time axis subsequent bounds setting.
*/
public NonTimeAxisSubsequentBoundsSetting getNonTimeAxisSubsequentMinSetting();
/**
* Return the plot's mode when data exceeds the current maximum bound of the non time axis.
* @return non-time axis subsequent bounds settings.
*/
public NonTimeAxisSubsequentBoundsSetting getNonTimeAxisSubsequentMaxSetting();
/**
* Return the value specified initially as the non time axis minimum bound.
* @return double initial non-time minimal setting.
*/
public double getInitialNonTimeMinSetting();
/**
* Return the value specified initially as the non time axis maximum bound.
* @return double initial non-time maximum setting.
*/
public double getInitialNonTimeMaxSetting();
/**
* Return the value specified initially as the time axis minimum bound.
* @return initial time minimal setting.
*/
public long getInitialTimeMinSetting();
/**
* Return the value specified initially as the time axis maximum bound.
* @return long initial time maximum setting.
*/
public long getInitialTimeMaxSetting();
/**
* Return the percentage padding to apply when expanding the time axis.
* @return double time padding.
*/
public double getTimePadding();
/**
* Return the percentage padding to apply when expanding the non time axis minimum bound.
* @return double non-time minimal padding.
*/
public double getNonTimeMinPadding();
/**
* Return the percentage padding to apply when expanding the non time axis minimum bound.
* @return double non-time maximum padding.
*/
public double getNonTimeMaxPadding();
/**
* Return true if the ordinal position should be used to group stacked plots.
* @return true if ordinal position should be used, false if existing collection structure should be used.
*/
public boolean getOrdinalPositionInStackedPlot();
/**
* Return true if the time sync line is visible. False otherwise.
* @return boolean flag for time sync line visible.
*/
public boolean isTimeSyncLineVisible();
/**
* Inform the plotting package of its related plotAbstraction.
* @param plotView related plotAbstraction.
*/
public void setPlotView(PlotAbstraction plotView);
/**
* Notify that time synchronization mode is to end.
*/
public void notifyGlobalTimeSyncFinished();
/**
* Return true if plot is in time sync mode.
* @return boolean flag to check whether in time sync mode.
*/
public boolean inTimeSyncMode();
/**
* Return the largest value currently displayed on the plot.
* @return double non-time maximum data value currently displayed.
*/
public double getNonTimeMaxDataValueCurrentlyDisplayed();
/**
* Return the smallest value currently displayed on the plot.
* @return double non-time minimal data value currently displayed.
*/
public double getNonTimeMinDataValueCurrentlyDisplayed();
/**
* Set the compression mode of the plot to state.
* @param state boolean flag.
*/
public void setCompressionEnabled(boolean state);
/**
* Return true if plot data compression is enabled, false otherwise.
* @return boolean is compression enabled.
*/
public boolean isCompresionEnabled();
/**
* Inform the plot that a data buffer update event has started.
*/
public void informUpdateCachedDataStreamStarted();
/**
* Inform the plot that a data buffer update event has finished.
*/
public void informUpdateCacheDataStreamCompleted();
/**
* Inform the plot that a regular data stream update event has started.
*/
public void informUpdateFromLiveDataStreamStarted();
/**
* Inform the plot that a regular data stream update event has ended.
*/
public void informUpdateFromLiveDataStreamCompleted();
/**
* Instruct the plot to set its time axis start and stop to the specified times.
* @param startTime plot start time.
* @param endTime plot end time.
*/
public void setTimeAxisStartAndStop(long startTime, long endTime);
/**
* Instruct plot to clear all data.
*/
public void clearAllDataFromPlot();
/**
* Pauses the plot if the argument is true, unpauses it otherwise.
* @param b true to pause the plot.
*/
public void pause(boolean b);
/**
* Returns true if the plot is paused.
* @return true if the plot is paused.
*/
public boolean isPaused();
/**
* Returns the non-time axis.
* @return the non-time axis.
*/
public Axis getNonTimeAxis();
/**
* Updates the visibility of the corner reset buttons based on which axes are pinned and what data is visible.
*/
public void updateResetButtons();
/**
* Setter/Getter for Plot Legend Labeling Algorithm.
* @param thePlotLabelingAlgorithm the plotting labeling algorithm based upon the table algorithm.
*/
public void setPlotLabelingAlgorithm(AbbreviatingPlotLabelingAlgorithm thePlotLabelingAlgorithm);
/**
* Gets the plot labeling algorithm instance.
* @return abbreviating plot labeling algorithm.
*/
public AbbreviatingPlotLabelingAlgorithm getPlotLabelingAlgorithm();
/**
* Adds the data points per feed Id.
* @param feedID feed identifier.
* @param points sorted map of points.
*/
public void addData(String feedID, SortedMap<Long, Double> points);
/**
* Adds the data per feed Id, timestamp and telemetry value.
* @param feed - feed Id.
* @param time - timestamp.
* @param value - telemetry value.
*/
public void addData(String feed, long time, double value);
/**
* Sets the minimal truncation value for telemetry point.
* @param min minimal value
*/
public void setTruncationPoint(double min);
/**
* Updates the compression ratio.
*/
public void updateCompressionRatio();
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_AbstractPlottingPackage.java |
583 | public class HighPrecisionLinearRegression {
private double[] x;
private double[] y;
private BigDecimal meanX;
private BigDecimal meanY;
private BigDecimal slope = null;
private BigDecimal intercept = null;
private BigDecimal stndDevX;
private BigDecimal stndDevY;
private static int requiredPrecision = 40;
public HighPrecisionLinearRegression(double[] x, double[] y) {
this.x = x;
this.y = y;
compute();
}
/** Compute the slope and intercept values from input x and y values.
*
*/
private void compute() {
int n = x.length;
List<BigDecimal> xList = new ArrayList<BigDecimal>();
List<BigDecimal> yList = new ArrayList<BigDecimal>();
List<BigDecimal> x2List = new ArrayList<BigDecimal>();
List<BigDecimal> y2List = new ArrayList<BigDecimal>();
List<BigDecimal> xyList = new ArrayList<BigDecimal>();
for (int i = 0; i < n; i++) {
try {
xList.add(BigDecimal.valueOf(x[i]));
} catch (Exception e) {
System.out.println(e.getMessage() + " x[i]: "+ x[i]);
}
yList.add(BigDecimal.valueOf(y[i]));
x2List.add(BigDecimal.valueOf(x[i]).multiply(BigDecimal.valueOf(x[i]), new MathContext(requiredPrecision, RoundingMode.HALF_EVEN)));
y2List.add(BigDecimal.valueOf(y[i]).multiply(BigDecimal.valueOf(y[i]), new MathContext(requiredPrecision, RoundingMode.HALF_EVEN)));
xyList.add(BigDecimal.valueOf(x[i]).multiply(BigDecimal.valueOf(y[i]), new MathContext(requiredPrecision, RoundingMode.HALF_EVEN)));
}
BigDecimal sumx = BigDecimal.valueOf(0.00000),
sumx2 = BigDecimal.valueOf(0.00000),
sumxy = BigDecimal.valueOf(0.00000),
slopeNumerator = BigDecimal.valueOf(0.00),
slopeDenominator = BigDecimal.valueOf(0.00);
sumx = sum(xList);
sumxy = sum(xyList);
sumx2 = sum(x2List);
meanX = mean(xList, new MathContext(requiredPrecision, RoundingMode.HALF_EVEN));
meanY = mean(yList, new MathContext(requiredPrecision, RoundingMode.HALF_EVEN));
slopeNumerator = sumxy.subtract(sumx.multiply(meanY, new MathContext(requiredPrecision, RoundingMode.HALF_EVEN)),
new MathContext(requiredPrecision, RoundingMode.HALF_EVEN));
slopeDenominator = sumx2.subtract(sumx.multiply(meanX, new MathContext(requiredPrecision, RoundingMode.HALF_EVEN)),
new MathContext(requiredPrecision, RoundingMode.HALF_EVEN));
if (slopeDenominator.compareTo(BigDecimal.valueOf(0.0)) == 0) {
slope = null;
intercept = null;
} else {
slope = slopeNumerator.divide(slopeDenominator, new MathContext(requiredPrecision, RoundingMode.HALF_EVEN));
intercept = meanY.subtract(slope.multiply(meanX));
}
}
/** Get the calculated slope as double value; return null if NaN.
* @return slope as dboule
*/
public double getSlope() {
if (slope == null) {
return Double.NaN;
}
return slope.doubleValue();
}
/** Get the calculated slope as double value; return null if NaN.
* @return slope as BigDecimal
*/
public BigDecimal getSlopeAsBigDecimal() {
return slope;
}
/** Get the calculated intercept as BigDecimal
* @return intercept the calculated interecept
*/
public BigDecimal getIntercept() {
return intercept;
}
/** Calculate and return the mean squared error.
* @return the mean squared error
*/
public double getRSquared() {
double r = slope.multiply(stndDevX).divide(stndDevY, BigDecimal.ROUND_HALF_EVEN).doubleValue();
return r * r;
}
/** Get the x values.
* @return x
*/
public double[] getX() {
return x;
}
/**Returns Y=mX+b with full precision, no rounding of numbers.
* @return the model
*/
public String getModel(){
return "Y= "+slope+"X + "+intercept+" RSqrd="+getRSquared();
}
/**Returns Y=mX+b .
* @return the rounded model
*/
public String getRoundedModel(){
return "Y= "+formatNumber(slope.doubleValue(),8)+"X + "+formatNumber(intercept.doubleValue(),3)+" RSqrd="+ formatNumber(getRSquared(),3);
}
/**Calculate Y given X.
* @return calculated Y
*/
public double calculateY (double x){
return slope.doubleValue()*x+intercept.doubleValue();
}
/**Calculate X given Y.
* @return calculated X
*/
public double calculateX (double y){
return (y-intercept.doubleValue())/slope.doubleValue();
}
/**Converts a double ddd.dddddddd to a user-determined number of decimal places right of the period.
* @return formatted number as string
*/
public static String formatNumber(double num, int numberOfDecimalPlaces){
NumberFormat f = NumberFormat.getNumberInstance();
f.setMaximumFractionDigits(numberOfDecimalPlaces);
f.setMinimumFractionDigits(numberOfDecimalPlaces);
return f.format(num);
}
public static final BigDecimal TWO = BigDecimal.valueOf(2);
/**
* Returns the sum number in the numbers list.
*
* @param numbers the numbers to calculate the sum.
* @return the sum of the numbers.
*/
public static BigDecimal sum(List<BigDecimal> numbers) {
BigDecimal sum = new BigDecimal(0);
for (BigDecimal bigDecimal : numbers) {
sum = sum.add(bigDecimal);
}
return sum;
}
/**
* Returns the mean number in the numbers list.
*
* @param numbers the numbers to calculate the mean.
* @param context the MathContext.
* @return the mean of the numbers.
*/
public static BigDecimal mean(List<BigDecimal> numbers, MathContext context) {
BigDecimal sum = sum(numbers);
return sum.divide(new BigDecimal(numbers.size()), context);
}
/**
* Returns the min number in the numbers list.
*
* @param numbers the numbers to calculate the min.
* @return the min number in the numbers list.
*/
public static BigDecimal min(List<BigDecimal> numbers) {
return new TreeSet<BigDecimal>(numbers).first();
}
/**
* Returns the max number in the numbers list.
*
* @param numbers the numbers to calculate the max.
* @return the max number in the numbers list.
*/
public static BigDecimal max(List<BigDecimal> numbers) {
return new TreeSet<BigDecimal>(numbers).last();
}
/**
* Returns the standard deviation of the numbers.
* Used in calcuation of either slope or R-squared.
* Double.NaN is returned if the numbers list is empty.
*
* @param numbers the numbers to calculate the standard deviation.
* @param biasCorrected true if variance is calculated by dividing by n - 1. False if by n. stddev is a sqrt of the
* variance.
* @param context the MathContext
* @return the standard deviation
*/
public static BigDecimal stddev(List<BigDecimal> numbers, boolean biasCorrected, MathContext context) {
BigDecimal stddev;
int n = numbers.size();
if (n > 0) {
if (n > 1) {
stddev = sqrt(var(numbers, biasCorrected, context));
}
else {
stddev = BigDecimal.ZERO;
}
}
else {
stddev = BigDecimal.valueOf(Double.NaN);
}
return stddev;
}
/**
* Computes the variance of the available values. By default, the unbiased "sample variance" definitional formula is
* used: variance = sum((x_i - mean)^2) / (n - 1)
* <p/>
* The "population variance" ( sum((x_i - mean)^2) / n ) can also be computed using this statistic. The
* <code>biasCorrected</code> property determines whether the "population" or "sample" value is returned by the
* <code>evaluate</code> and <code>getResult</code> methods. To compute population variances, set this property to
* <code>false</code>.
*
* @param numbers the numbers to calculate the variance.
* @param biasCorrected true if variance is calculated by dividing by n - 1. False if by n.
* @param context the MathContext
* @return the variance of the numbers.
*/
public static BigDecimal var(List<BigDecimal> numbers, boolean biasCorrected, MathContext context) {
int n = numbers.size();
if (n == 0) {
return BigDecimal.valueOf(Double.NaN);
}
else if (n == 1) {
return BigDecimal.ZERO;
}
BigDecimal mean = mean(numbers, context);
List<BigDecimal> squares = new ArrayList<BigDecimal>();
for (BigDecimal number : numbers) {
BigDecimal XminMean = number.subtract(mean);
squares.add(XminMean.pow(2, context));
}
BigDecimal sum = sum(squares);
return sum.divide(new BigDecimal(biasCorrected ? numbers.size() - 1 : numbers.size()), context);
}
/**
* Calculates the square root of the number.
*
* @param number the input number.
* @return the square root of the input number.
*/
public static BigDecimal sqrt(BigDecimal number) {
int digits; // final precision
BigDecimal numberToBeSquareRooted;
BigDecimal iteration1;
BigDecimal iteration2;
BigDecimal temp1 = null;
BigDecimal temp2 = null; // temp values
int extraPrecision = number.precision();
MathContext mc = new MathContext(extraPrecision, RoundingMode.HALF_UP);
numberToBeSquareRooted = number; // bd global variable
double num = numberToBeSquareRooted.doubleValue(); // bd to double
if (mc.getPrecision() == 0)
throw new IllegalArgumentException("\nRoots need a MathContext precision > 0");
if (num < 0.)
throw new ArithmeticException("\nCannot calculate the square root of a negative number");
if (num == 0.)
return number.round(mc); // return sqrt(0) immediately
if (mc.getPrecision() < 50) // small precision is buggy..
extraPrecision += 10; // ..make more precise
int startPrecision = 1; // default first precision
/* create the initial values for the iteration procedure:
* x0: x ~ sqrt(d)
* v0: v = 1/(2*x)
*/
if (num == Double.POSITIVE_INFINITY) // d > 1.7E308
{
BigInteger bi = numberToBeSquareRooted.unscaledValue();
int biLen = bi.bitLength();
int biSqrtLen = biLen / 2; // floors it too
bi = bi.shiftRight(biSqrtLen); // bad guess sqrt(d)
iteration1 = new BigDecimal(bi); // x ~ sqrt(d)
MathContext mm = new MathContext(5, RoundingMode.HALF_DOWN); // minimal precision
extraPrecision += 10; // make up for it later
iteration2 = BigDecimal.ONE.divide(TWO.multiply(iteration1, mm), mm); // v = 1/(2*x)
}
else // d < 1.7E10^308 (the usual numbers)
{
double s = Math.sqrt(num);
iteration1 = new BigDecimal(s); // x = sqrt(d)
iteration2 = new BigDecimal(1. / 2. / s); // v = 1/2/x
// works because Double.MIN_VALUE * Double.MAX_VALUE ~ 9E-16, so: v > 0
startPrecision = 64;
}
digits = mc.getPrecision() + extraPrecision; // global limit for procedure
// create initial MathContext(precision, RoundingMode)
MathContext n = new MathContext(startPrecision, mc.getRoundingMode());
return sqrtProcedure(n, digits, numberToBeSquareRooted, iteration1, iteration2, temp1, temp2); // return square root using argument precision
}
/**
* Square root by coupled Newton iteration, sqrtProcedure() is the iteration part I adopted the Algorithm from the
* book "Pi-unleashed", so now it looks more natural I give sparse math comments from the book, it assumes argument
* mc precision >= 1
*
* @param mc
* @param digits
* @param numberToBeSquareRooted
* @param iteration1
* @param iteration2
* @param temp1
* @param temp2
* @return
*/
private static BigDecimal sqrtProcedure(MathContext mc, int digits, BigDecimal numberToBeSquareRooted, BigDecimal iteration1,
BigDecimal iteration2, BigDecimal temp1, BigDecimal temp2) {
// next v // g = 1 - 2*x*v
temp1 = BigDecimal.ONE.subtract(TWO.multiply(iteration1, mc).multiply(iteration2, mc), mc);
iteration2 = iteration2.add(temp1.multiply(iteration2, mc), mc); // v += g*v ~ 1/2/sqrt(d)
// next x
temp2 = numberToBeSquareRooted.subtract(iteration1.multiply(iteration1, mc), mc); // e = d - x^2
iteration1 = iteration1.add(temp2.multiply(iteration2, mc), mc); // x += e*v ~ sqrt(d)
// increase precision
int m = mc.getPrecision();
if (m < 2)
m++;
else
m = m * 2 - 1; // next Newton iteration supplies so many exact digits
if (m < 2 * digits) // digits limit not yet reached?
{
mc = new MathContext(m, mc.getRoundingMode()); // apply new precision
sqrtProcedure(mc, digits, numberToBeSquareRooted, iteration1, iteration2, temp1, temp2); // next iteration
}
return iteration1; // returns the iterated square roots
}
/**An example.*/
/* public static void main(String[] args) {
double[] x = {
95, 85, 80, 70, 60
1339714487419.9426,
1339714489478.618,
1339714491537.293,
1339714493595.9683,
1339714495654.6433,
1339714497713.3184,
1339714499771.9937,
1339714501830.6687,
1339714501443.9172,
1339714503502.5923
};
double[] y = {
85, 95, 70, 65, 70
// 12.18, 11.25, 16.47, 13.72, 18.73, 15.61, 19.46, 17.76, 17.76, 24.5
};
HighPrecisionLinearRegression lr = new HighPrecisionLinearRegression(x, y);
System.out.println(lr.getRoundedModel());
}*/
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_HighPrecisionLinearRegression.java |
584 | @SuppressWarnings("serial")
public class LegendEntry extends JPanel implements MouseListener {
private final static Logger logger = LoggerFactory.getLogger(LegendEntry.class);
// Padding around labels to create space between the label text and its outside edge
// Add a little spacing from the left-hand side
private static final int LEFT_PADDING = 5;
private static final Border PANEL_PADDING = BorderFactory.createEmptyBorder(0, LEFT_PADDING, 0, 0);
private static final Border EMPTY_BORDER = BorderFactory.createEmptyBorder(1,1,1,1);
private Border focusBorder = BorderFactory.createLineBorder(LafColor.TEXT_HIGHLIGHT);
// Associated plot.
private LinearXYPlotLine linePlot;
// Gui widgets
protected JLabel baseDisplayNameLabel= new TruncatingLabel();
private Color backgroundColor;
private Color foregroundColor;
private Color originalPlotLineColor;
private Stroke originalPlotLineStroke;
private Stroke originalRegressionLineStroke;
private Font originalFont;
private Font boldFont;
private Font strikeThruFont;
private Font boldStrikeThruFont;
private String baseDisplayName = "";
boolean selected=false;
private String currentToolTipTxt = "";
private ToolTipManager toolTipManager;
private String thisBaseDisplayName = "";
private String valueString = "";
private AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm = new AbbreviatingPlotLabelingAlgorithm();
private String computedBaseDisplayName = "";
private FeedProvider.RenderingInfo renderingInfo;
private LegendEntryPopupMenuFactory popupManager = null;
private LineSettings lineSettings = new LineSettings();
// Default width - will be adjusted to match base display name
private int baseWidth = PlotConstants.PLOT_LEGEND_WIDTH;
private LinearXYPlotLine regressionLine;
/**
* Construct a legend entry
* @param theBackgroundColor background color of the entry
* @param theForegroundColor text color
* @param font text font
*/
LegendEntry(Color theBackgroundColor, Color theForegroundColor, Font font, AbbreviatingPlotLabelingAlgorithm thisPlotLabelingAlgorithm) {
setBorder(EMPTY_BORDER);
plotLabelingAlgorithm = thisPlotLabelingAlgorithm;
backgroundColor = theBackgroundColor;
foregroundColor = theForegroundColor;
setForeground(foregroundColor);
lineSettings.setMarker(lineSettings.getColorIndex());
// Default to using same marker index as color index; may be later overridden if user-specified
focusBorder = BorderFactory.createLineBorder(theForegroundColor);
// NOTE: Original font size is 10. Decrease by 1 to size 9.
// Need to explicitly cast to float from int on derived font size
// Need to explicitly set to FontName=ArialMT/Arial-BoldMT and FontFamily=Arial to be
// cross OS platforms L&F between MacOSX and Linux.
// MacOSX defaults to Arial and Linux defaults to Dialog FontFamily.
originalFont = font;
originalFont = originalFont.deriveFont((float)(originalFont.getSize()-1));
boldFont = originalFont.deriveFont(Font.BOLD);
Map<TextAttribute, Object> attributes = new Hashtable<TextAttribute, Object>();
attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
strikeThruFont = originalFont.deriveFont(attributes);
boldStrikeThruFont = boldFont.deriveFont(attributes);
// Setup the look of the labels.
baseDisplayNameLabel.setBackground(backgroundColor);
baseDisplayNameLabel.setForeground(foregroundColor);
baseDisplayNameLabel.setFont(originalFont);
baseDisplayNameLabel.setOpaque(true);
// Sets as the default ToolTipManager
toolTipManager = ToolTipManager.sharedInstance();
toolTipManager.setEnabled(true);
toolTipManager.setLightWeightPopupEnabled(true);
// Defaults: toolTipManager.getDismissDelay()=4000ms,
// toolTipManager.getInitialDelay()=750ms,
// toolTipManager.getReshowDelay()=500ms
toolTipManager.setDismissDelay(PlotConstants.MILLISECONDS_IN_SECOND * 3);
toolTipManager.setInitialDelay(PlotConstants.MILLISECONDS_IN_SECOND / 2);
toolTipManager.setReshowDelay(PlotConstants.MILLISECONDS_IN_SECOND / 2);
// Place the labels according to the format specified in the UE spec.
layoutLabels();
// Listen to mouse events to drive the highlighting of legends when mouse enters.
addMouseListener(this);
}
// Data getter and and setters
void setPlot(LinearXYPlotLine thePlot) {
linePlot = thePlot;
updateLinePlotFromSettings();
}
private List<String> getPanelOrWindowContextTitleList() {
List<String> panelOrWindowContextTitleList = new ArrayList<String>();
panelOrWindowContextTitleList.clear();
if (plotLabelingAlgorithm != null) {
if (plotLabelingAlgorithm.getPanelContextTitleList().size() > 0) {
panelOrWindowContextTitleList.addAll(this.plotLabelingAlgorithm.getPanelContextTitleList());
}
if (plotLabelingAlgorithm.getCanvasContextTitleList().size() > 0) {
panelOrWindowContextTitleList.addAll(this.plotLabelingAlgorithm.getCanvasContextTitleList());
}
} else {
logger.error("Plot labeling algorithm object is NULL!");
}
return panelOrWindowContextTitleList;
}
public void setBaseDisplayName(String theBaseDisplayName) {
thisBaseDisplayName = theBaseDisplayName;
if (thisBaseDisplayName != null) {
thisBaseDisplayName = thisBaseDisplayName.trim();
}
baseDisplayName = thisBaseDisplayName;
// Format the base display name
// Split string around newline character.
String[] strings = baseDisplayName.split(PlotConstants.LEGEND_NEWLINE_CHARACTER);
if (strings.length <= 1) {
// Determine if first or second string is null
if (baseDisplayName.indexOf(PlotConstants.LEGEND_NEWLINE_CHARACTER) == -1) {
// first string is null.
baseDisplayNameLabel.setText(baseDisplayName);
} else if (theBaseDisplayName.equals(PlotConstants.LEGEND_NEWLINE_CHARACTER)) {
baseDisplayNameLabel.setText("");
} else {
// second string is empty. Truncate first.
baseDisplayNameLabel.setText(PlotConstants.LEGEND_ELLIPSES);
}
} else {
// Use table labeling algorithm to display base display name.
// line1 is base display name; while line2 is PUI name
String line1 = strings[0];
if (line1 != null) {
baseDisplayName = line1.trim();
thisBaseDisplayName = baseDisplayName;
}
List<String> baseDisplayNameList = new ArrayList<String>();
baseDisplayNameList.add(line1);
assert plotLabelingAlgorithm != null : "Plot labeling algorithm should NOT be NULL at this point.";
baseDisplayName = plotLabelingAlgorithm.computeLabel(baseDisplayNameList, getPanelOrWindowContextTitleList());
// since this name will be used in a legend, it must not be empty so use the initial display name if it would have been empty
if (baseDisplayName != null && baseDisplayName.isEmpty()) {
baseDisplayName = thisBaseDisplayName;
}
computedBaseDisplayName = baseDisplayName;
updateLabelText();
}
thisBaseDisplayName = theBaseDisplayName.replaceAll(PlotConstants.WORD_DELIMITERS, " ");
currentToolTipTxt = "<HTML>" + thisBaseDisplayName.replaceAll(PlotConstants.LEGEND_NEWLINE_CHARACTER, "<BR>") + "<BR>" + valueString + "<HTML>";
this.setToolTipText(currentToolTipTxt);
}
void setData(FeedProvider.RenderingInfo info) {
this.renderingInfo = info;
String valueText = info.getValueText();
if (!"".equals(valueText)) {
valueString = PlotConstants.DECIMAL_FORMAT.format(Double.parseDouble(valueText));
}
updateLabelFont();
updateLabelText();
thisBaseDisplayName = thisBaseDisplayName.replaceAll(PlotConstants.WORD_DELIMITERS, " ");
currentToolTipTxt = "<HTML>" + thisBaseDisplayName.replaceAll(PlotConstants.LEGEND_NEWLINE_CHARACTER, "<BR>") + "<BR>" + valueString + "<HTML>";
this.setToolTipText(currentToolTipTxt);
}
private void updateLabelFont() {
if(selected) {
if(renderingInfo == null || renderingInfo.isPlottable()) {
baseDisplayNameLabel.setFont(boldFont);
} else {
baseDisplayNameLabel.setFont(boldStrikeThruFont);
}
} else {
if(renderingInfo == null || renderingInfo.isPlottable()) {
baseDisplayNameLabel.setFont(originalFont);
} else {
baseDisplayNameLabel.setFont(strikeThruFont);
}
}
}
private void updateLabelText() {
String statusText = renderingInfo == null ? null : renderingInfo.getStatusText();
if(statusText == null) {
statusText = "";
}
statusText = statusText.trim();
if(!"".equals(statusText)) {
baseDisplayNameLabel.setText("(" + statusText + ") " + baseDisplayName);
} else {
baseDisplayNameLabel.setText(baseDisplayName);
}
}
private void updateLabelWidth() {
/* Record font & string to restore*/
Font f = baseDisplayNameLabel.getFont();
String s = baseDisplayNameLabel.getText();
if (f == originalFont && s.equals(baseDisplayName) && baseDisplayNameLabel.isValid()) {
baseWidth = baseDisplayNameLabel.getWidth();
}
}
/**
* Layout the labels within a legend in line with the UE specification.
*/
void layoutLabels() {
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setBorder(PANEL_PADDING);
panel.setBackground(backgroundColor);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JPanel displayNamePanel = new JPanel();
displayNamePanel.setLayout(new BoxLayout(displayNamePanel, BoxLayout.LINE_AXIS));
displayNamePanel.add(baseDisplayNameLabel);
displayNamePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(displayNamePanel);
add(panel, BorderLayout.CENTER);
}
@Override
public void mouseClicked(MouseEvent e) {
// do nothing
}
@Override
public void mouseEntered(MouseEvent e) {
toolTipManager.registerComponent(this);
if (!selected) {
// Highlight this entry on the plot.
originalPlotLineColor = linePlot.getForeground();
originalPlotLineStroke = linePlot.getStroke();
}
selected = true;
// Highlight this legend entry
baseDisplayNameLabel.setForeground(foregroundColor.brighter());
updateLabelFont();
// Highlight this entry on the plot.
originalPlotLineColor = linePlot.getForeground();
originalPlotLineStroke = linePlot.getStroke();
linePlot.setForeground(originalPlotLineColor.brighter().brighter());
if(originalPlotLineStroke == null) {
linePlot.setStroke(new BasicStroke(PlotConstants.SELECTED_LINE_THICKNESS));
} else if (originalPlotLineStroke instanceof BasicStroke) {
BasicStroke stroke = (BasicStroke) originalPlotLineStroke;
linePlot.setStroke(new BasicStroke(stroke.getLineWidth() * PlotConstants.SELECTED_LINE_THICKNESS, stroke.getEndCap(), stroke
.getLineJoin(), stroke.getMiterLimit(), stroke.getDashArray(), stroke.getDashPhase()));
} //Otherwise, it's a stroke we can't change (ie EMPTY_STROKE)
if (regressionLine != null) {
originalRegressionLineStroke = regressionLine.getStroke();
regressionLine.setForeground(originalPlotLineColor.brighter().brighter());
Stroke stroke = (BasicStroke) regressionLine.getStroke();
//TODO synch with plot thickness feature changes
if(stroke == null) {
regressionLine.setStroke(new BasicStroke(PlotConstants.SLOPE_LINE_WIDTH*2,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, PlotConstants.dash1, 0.0f));
} else {
regressionLine.setStroke(new BasicStroke(PlotConstants.SLOPE_LINE_WIDTH*2,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, PlotConstants.dash1, 0.0f));
}
}
this.setToolTipText(currentToolTipTxt);
}
@Override
public void mouseExited(MouseEvent e) {
toolTipManager.unregisterComponent(this);
selected = false;
// Return this legend entry to its original look.
baseDisplayNameLabel.setForeground(foregroundColor);
updateLabelFont();
// Return this entry on the plot to its original look.
linePlot.setForeground(originalPlotLineColor);
linePlot.setStroke(originalPlotLineStroke);
if (regressionLine != null) {
regressionLine.setForeground(originalPlotLineColor);
regressionLine.setStroke(originalRegressionLineStroke);
}
}
@Override
public void mousePressed(MouseEvent e) {
// open the color changing popup
if (popupManager != null && e.isPopupTrigger()) {
setBorder(focusBorder); //TODO: Externalize the color of this?
JPopupMenu popup = popupManager.getPopup(this);
popup.show(this, e.getX(), e.getY());
popup.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuCanceled(PopupMenuEvent arg0) {
setBorder(EMPTY_BORDER);
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
setBorder(EMPTY_BORDER);
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {
}
});
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (popupManager != null && e.isPopupTrigger()) {
popupManager.getPopup(this).show(this, e.getX(), e.getY());
}
}
public String getToolTipText() {
return currentToolTipTxt;
}
// Retrieves whatever is set in the label text field
public String getBaseDisplayNameLabel() {
return baseDisplayNameLabel.getText();
}
// Retrieves base display name + PUI name
public String getFullBaseDisplayName() {
return thisBaseDisplayName;
}
// Retrieves only base display name (w/o PUI name)
// after running thru labeling algorithm
public String getComputedBaseDisplayName() {
return computedBaseDisplayName;
}
// Retrieves truncated with ellipse
public String getTruncatedBaseDisplayName() {
return baseDisplayName;
}
public void setPlotLabelingAlgorithm(AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm) {
this.plotLabelingAlgorithm = plotLabelingAlgorithm;
}
public AbbreviatingPlotLabelingAlgorithm getPlotLabelingAlgorithm() {
return this.plotLabelingAlgorithm;
}
public int getLabelWidth() {
updateLabelWidth();
return baseWidth + LEFT_PADDING;
}
@Override
public void setForeground(Color fg) {
Color lineColor = fg;
Color labelColor = fg;
if (linePlot != null) {
if (linePlot.getForeground() != foregroundColor) lineColor = fg;
linePlot.setForeground(lineColor);
}
if (regressionLine != null) {
if (regressionLine.getForeground() != foregroundColor) lineColor = fg.brighter().brighter();
regressionLine.setForeground(lineColor);
}
if (baseDisplayNameLabel != null) {
if (baseDisplayNameLabel.getForeground() != foregroundColor) labelColor = fg.brighter();
baseDisplayNameLabel.setForeground(labelColor);
}
foregroundColor = fg;
focusBorder = BorderFactory.createLineBorder(fg);
// Infer the appropriate index for this color
for (int i = 0; i < PlotConstants.MAX_NUMBER_OF_DATA_ITEMS_ON_A_PLOT; i++) {
if (PlotLineColorPalette.getColor(i).getRGB() == fg.getRGB()) {
lineSettings.setColorIndex(i);
}
}
super.setForeground(fg);
}
public LegendEntryPopupMenuFactory getPopup() {
return popupManager;
}
public void setPopup(LegendEntryPopupMenuFactory popup) {
this.popupManager = popup;
}
public void setLineSettings(LineSettings settings) {
lineSettings = settings;
updateLinePlotFromSettings();
}
public LineSettings getLineSettings() {
return lineSettings;
}
private void updateLinePlotFromSettings() {
/* Color */
int index = lineSettings.getColorIndex();
Color c = PlotLineColorPalette.getColor(index);
setForeground(c);
/* Thickness */
Stroke s = linePlot.getStroke();
if (s == null || s instanceof BasicStroke) {
int t = lineSettings.getThickness();
linePlot.setStroke(t == 1 ? null : new BasicStroke(t));
originalPlotLineStroke = linePlot.getStroke();
} // We only want to modify known strokes
/* Marker */
if (linePlot.getPointIcon() != null) {
Shape shape = null;
if (lineSettings.getUseCharacter()) {
Graphics g = (Graphics) getGraphics();
if (g != null && g instanceof Graphics2D) {
FontRenderContext frc = ((Graphics2D)g).getFontRenderContext();
shape = PlotLineShapePalette.getShape(lineSettings.getCharacter(), frc);
}
} else {
int marker = lineSettings.getMarker();
shape = PlotLineShapePalette.getShape(marker);
}
if (shape != null) {
linePlot.setPointIcon(new PlotMarkerIcon(shape));
baseDisplayNameLabel.setIcon(new PlotMarkerIcon(shape, false, 12, 12));
}
}
linePlot.repaint();
repaint();
}
/** Get whether a regression line is displayed or not.
* @return regressionLine
*/
public boolean hasRegressionLine() {
return lineSettings.getHasRegression();
}
/** Set whether a regression line is displayed or not.
* @param regressionLine boolean indicator
*/
public void setHasRegressionLine(boolean regressionLine) {
lineSettings.setHasRegression(regressionLine);
}
/** Get the number of regression points to use.
* @return numberRegressionPoints the number of regression points to use
*/
public int getNumberRegressionPoints() {
return lineSettings.getRegressionPoints();
}
/** Set the number of regression points to use.
* @param numberRegressionPoints
*/
public void setNumberRegressionPoints(int numberRegressionPoints) {
lineSettings.setRegressionPoints(numberRegressionPoints);
}
/** Get the regression line for this legend entry.
* @return regressionLine a LinearXYPlotLine
*/
public LinearXYPlotLine getRegressionLine() {
return regressionLine;
}
/** Set the regression line for this legend entry.
* @param regressionLine a LinearXYPlotLine
*/
public void setRegressionLine(LinearXYPlotLine regressionLine) {
this.regressionLine = regressionLine;
if (regressionLine != null)
regressionLine.setForeground(foregroundColor);
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_LegendEntry.java |
585 | popup.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuCanceled(PopupMenuEvent arg0) {
setBorder(EMPTY_BORDER);
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
setBorder(EMPTY_BORDER);
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {
}
}); | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_LegendEntry.java |
586 | @SuppressWarnings("serial")
public class LegendManager extends JPanel implements MouseListener {
public static final int MAX_NUMBER_LEGEND_COLUMNS = 1;
private PlotterPlot plot;
// Panel holding the legend items.
private JPanel innerPanel;
private Color backgroundColor;
private LegendEntry legendEntry;
private AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm = new AbbreviatingPlotLabelingAlgorithm();
private List<LegendEntry> legendEntryList = new ArrayList<LegendEntry> ();
/**
* Included only to support unit testing.
*/
protected LegendManager() {}
/**
* Construct the legend panel for a plot
* @param legendBackgroundColor the background color of the legend
*/
LegendManager(PlotterPlot thePlot, Color legendBackgroundColor, AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm) {
this.plotLabelingAlgorithm = plotLabelingAlgorithm;
plot = thePlot;
backgroundColor = legendBackgroundColor;
setBackground(legendBackgroundColor);
setLayout(new BorderLayout());
innerPanel = new JPanel();
innerPanel.setBackground(legendBackgroundColor);
innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS));
add(innerPanel, BorderLayout.NORTH);
setVisible(false);
plot.plotView.add(this);
}
/**
* Add new entry to the legend.
* @param entry to add
*/
public void addLegendEntry(LegendEntry entry) {
entry.setBackground(backgroundColor);
legendEntry = entry;
legendEntry.setPlotLabelingAlgorithm(this.plotLabelingAlgorithm);
legendEntryList.add(entry);
innerPanel.add(legendEntry);
}
public LegendEntry getLegendEntry() {
return legendEntry;
}
public List<LegendEntry> getLegendEntryList() {
return legendEntryList;
}
@Override
public void mouseClicked(MouseEvent e) {
//do nothing
}
@Override
public void mouseEntered(MouseEvent e) {
String toolTipText = legendEntry.getToolTipText();
legendEntry.setToolTipText(toolTipText);
this.setToolTipText(toolTipText);
}
@Override
public void mouseExited(MouseEvent e) {
//do nothing
}
@Override
public void mousePressed(MouseEvent e) {
//do nothing
}
@Override
public void mouseReleased(MouseEvent e) {
//do nothing
}
public String getToolTipText() {
return legendEntry.getToolTipText();
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_LegendManager.java |
587 | public class LinearRegression {
/**An example.*/
public static void main(String[] args) {
double[] x = {95, 85, 80, 70, 60};
double[] y = {85, 95, 70, 65, 70};
LinearRegression lr = new LinearRegression(x, y);
System.out.println(lr.getRoundedModel());
// System.out.println("calculate y given an x of 38 "+lr.calculateY(38));
// System.out.println("calculate x given a y of 41 "+lr.calculateX(41));
}
//fields
private double[] x;
private double[] y;
private double meanX;
private double meanY;
private double slope;
private double intercept;
private double stndDevX;
private double stndDevY;
//constructor
public LinearRegression(double[] x, double[] y) {
this.x = x;
this.y = y;
compute();
}
//methods
/**Performs linear regression*/
private void compute() {
double n = x.length;
double sumy = 0.0,
sumx = 0.0,
sumx2 = 0.0,
sumy2 = 0.0,
sumxy = 0.0;
for (int i = 0; i < n; i++) {
sumx += x[i];
sumx2 += x[i] * x[i];
sumy += y[i];
sumy2 += y[i] * y[i];
sumxy += x[i] * y[i];
}
meanX = sumx / n;
meanY = sumy / n;
slope = (sumxy - sumx * meanY) / (sumx2 - sumx * meanX);
intercept = meanY - slope * meanX;
stndDevX = Math.sqrt((sumx2 - sumx * meanX) / (n - 1));
stndDevY = Math.sqrt((sumy2 - sumy * meanY) / (n - 1));
}
/**Return approximated Y value, good for a single interpolation, multiple calls are inefficient!*/
public static double interpolateY(double x1, double y1, double x2, double y2, double fixedX ){
double[] x = {x1, x2};
double[] y = {y1, y2};
LinearRegression lr = new LinearRegression(x,y);
return lr.calculateY(fixedX);
}
/**Return approximated X value, good for a single interpolation, multiple calls are inefficient!*/
public static double interpolateX(double x1, double y1, double x2, double y2, double fixedY ){
double[] x = {x1, x2};
double[] y = {y1, y2};
LinearRegression lr = new LinearRegression(x,y);
return lr.calculateX(fixedY);
}
//getters
public double getSlope() {
return slope;
}
public double getIntercept() {
return intercept;
}
public double getRSquared() {
double r = slope * stndDevX / stndDevY;
return r * r;
}
public double[] getX() {
return x;
}
/**Returns Y=mX+b with full precision, no rounding of numbers.*/
public String getModel(){
return "Y= "+slope+"X + "+intercept+" RSqrd="+getRSquared();
}
/**Returns Y=mX+b */
public String getRoundedModel(){
return "Y= "+formatNumber(slope,3)+"X + "+formatNumber(intercept,3)+" RSqrd="+ formatNumber(getRSquared(),3);
}
/**Calculate Y given X.*/
public double calculateY (double x){
return slope*x+intercept;
}
/**Calculate X given Y.*/
public double calculateX (double y){
return (y-intercept)/slope;
}
/**Nulls the x and y arrays. Good to call before saving.*/
public void nullArrays(){
x = null;
y = null;
}
/**Converts a double ddd.dddddddd to a user determined number of decimal places right of the . */
public static String formatNumber(double num, int numberOfDecimalPlaces){
NumberFormat f = NumberFormat.getNumberInstance();
f.setMaximumFractionDigits(numberOfDecimalPlaces);
f.setMinimumFractionDigits(numberOfDecimalPlaces);
return f.format(num);
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_LinearRegression.java |
588 | public class LinearXYPlotLineWrapper extends LinearXYPlotLine {
private static final long serialVersionUID = -656948949864598815L;
private int xPadding = 0;
private int yPadding = 0;
public LinearXYPlotLineWrapper(XYAxis xAxis, XYAxis yAxis,
XYDimension independentDimension) {
super(xAxis, yAxis, independentDimension);
}
@Override
public void setStroke(Stroke stroke) {
super.setStroke(stroke);
calculatePadding();
}
@Override
public void setPointIcon(Icon icon) {
super.setPointIcon(icon);
calculatePadding();
}
@Override
public void repaint(long tm, int x, int y, int width, int height) {
super.repaint(tm, x - xPadding, y - yPadding, width + xPadding * 2, height + yPadding * 2);
}
@Override
public void repaint(int x, int y, int width, int height) {
super.repaint(x - xPadding, y - yPadding, width + xPadding * 2, height + yPadding * 2);
}
private void calculatePadding() {
int x = 0;
int y = 0;
Stroke s = getStroke();
if (s != null && s instanceof BasicStroke) {
x += ((BasicStroke) s).getLineWidth() / 2;
y += ((BasicStroke) s).getLineWidth() / 2;
}
Icon i = getPointIcon();
if (i != null) {
x += i.getIconWidth() / 2;
y += i.getIconHeight() / 2;
}
xPadding = x;
yPadding = y;
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_LinearXYPlotLineWrapper.java |
589 | @SuppressWarnings("serial")
public final class MarqueeZoomListener extends MouseAdapter {
private static final Color END_POINT_FOREGROUND = new Color(100, 0, 0);
private static final Color START_POINT_FOREGROUND = new Color(0, 100, 0);
private static final Color TRANSLUCENT_WHITE = new Color(255, 255, 255, 200);
private int clickX, clickY;
private Rectangle marqueeRect = null;
private MarqueeCanvas canvas;
private XYPlot xyPlot;
private int mouseStartX, mouseStartY, mouseEndX, mouseEndY;
private SimpleDateFormat dateFormat;
private PlotLocalControlsManager plotLocalControlsManager;
private Font labelFont;
private static Cursor ZOOM_IN_PLOT_CURSOR;
static {
Toolkit toolkit = Toolkit.getDefaultToolkit();
try {
Image image = ImageIO.read(MarqueeZoomListener.class.getResourceAsStream("/images/zoomCursor.png"));
Point cursorHotSpot = new Point(0,0);
ZOOM_IN_PLOT_CURSOR = toolkit.createCustomCursor(image, cursorHotSpot, "Zoom In Plot");
} catch (IOException e) {
ZOOM_IN_PLOT_CURSOR = Cursor.getDefaultCursor();
}
}
public MarqueeZoomListener(PlotLocalControlsManager plotLocalControlsManager, XYPlot xyPlot, SimpleDateFormat dateFormat, Font labelFont) {
this.xyPlot = xyPlot;
this.dateFormat = dateFormat;
this.plotLocalControlsManager = plotLocalControlsManager;
this.labelFont = labelFont;
}
@Override
public void mouseDragged(MouseEvent e) {
if (marqueeRect == null) {
// this method is invoked during each drag event, so dragStart tracks the start of the drag event
if (canvas != null) {
// check the cursor to see if the user is currently in a move or resize mode
// also verify whether the selected point is directly in the top level panel. This
// should prevent nested selections from triggering selections at the top level.
marqueeRect = new Rectangle();
clickX = mouseEndX = e.getX();
clickY = mouseEndY = e.getY();
marqueeRect.setBounds(e.getX(), e.getY(), 1, 1);
canvas.repaint();
}
} else {
mouseEndX = e.getX();
mouseEndY = e.getY();
if (mouseEndX >= clickX) {
if (mouseEndY >= clickY) {
// existing upper left point is unchanged, so just adjust
// the height, width
marqueeRect.setBounds(clickX, clickY, mouseEndX - clickX, mouseEndY - clickY);
} else {
// original click is now the lower left point
int width = mouseEndX - clickX;
marqueeRect.setBounds(mouseEndX - width, mouseEndY, width, clickY - mouseEndY);
}
} else {
if (mouseEndY >= clickY) {
// original click is now the upper right point
marqueeRect.setBounds(mouseEndX, clickY, clickX - mouseEndX, mouseEndY - clickY);
} else {
// original click is now the lower right point
marqueeRect.setBounds(mouseEndX, mouseEndY, clickX - mouseEndX, clickY - mouseEndY);
}
}
canvas.repaint();
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (canvas != null) {
xyPlot.getContents().remove(canvas);
Point2D startCoord = convertPointToLogicalCoord(mouseStartX, mouseStartY);
Point2D endCoord = convertPointToLogicalCoord(mouseEndX, mouseEndY);
XYAxis xAxis = xyPlot.getXAxis();
if (endCoord.getX() > startCoord.getX()) {
xAxis.setStart(startCoord.getX());
xAxis.setEnd(endCoord.getX());
} else {
xAxis.setStart(endCoord.getX());
xAxis.setEnd(startCoord.getX());
}
XYAxis yAxis = xyPlot.getYAxis();
if (endCoord.getY() > startCoord.getY()) {
yAxis.setStart(startCoord.getY());
yAxis.setEnd(endCoord.getY());
} else {
yAxis.setStart(endCoord.getY());
yAxis.setEnd(startCoord.getY());
}
plotLocalControlsManager.pinXYAxesAfterZoomedIn();
marqueeRect = null;
canvas = null;
xyPlot.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
@Override
public void mousePressed(MouseEvent e) {
int onmask = InputEvent.ALT_DOWN_MASK | InputEvent.BUTTON1_DOWN_MASK;
int offmask = InputEvent.CTRL_DOWN_MASK | InputEvent.META_DOWN_MASK;
if ((e.getModifiersEx() & (onmask | offmask)) == onmask) {
canvas = new MarqueeCanvas();
xyPlot.getContents().add(canvas);
xyPlot.getContents().setComponentZOrder(canvas, 0);
mouseStartX = e.getX();
mouseStartY = e.getY();
xyPlot.setCursor(ZOOM_IN_PLOT_CURSOR);
}
}
private Point2D convertPointToLogicalCoord(int x, int y) {
Point2D p = new Point2D.Double();
xyPlot.getContents().toLogical(p, new Point(x, y));
return p;
}
private class MarqueeCanvas extends JPanel {
private MessageFormat messageFormat = new MessageFormat(" (X: {0} Y: {1}) ");
public MarqueeCanvas() {
setOpaque(false);
setBackground(null);
}
@Override
public void paint(Graphics g) {
if (marqueeRect == null) {
super.paint(g);
return;
}
Graphics2D g2 = (Graphics2D) g;
RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setFont(labelFont);
FontMetrics fontMetrics = g2.getFontMetrics();
g2.setRenderingHints(renderHints);
g2.setStroke(new BasicStroke(1f,
BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_MITER,
1f,
new float[]{2f},
0.0f));
g2.setColor(Color.white);
g2.drawRect(marqueeRect.x, marqueeRect.y, marqueeRect.width, marqueeRect.height);
Point2D p = convertPointToLogicalCoord(mouseStartX, mouseStartY);
String startPoint = messageFormat.format(new Object[]{p.getX(), p.getY()});
messageFormat.setFormatByArgumentIndex(0, dateFormat);
messageFormat.setFormatByArgumentIndex(1, PlotConstants.DECIMAL_FORMAT);
g2.setColor(TRANSLUCENT_WHITE);
g2.fillRect(mouseStartX, mouseStartY - fontMetrics.getHeight() - 2, fontMetrics.stringWidth(startPoint), fontMetrics.getHeight());
g2.setColor(START_POINT_FOREGROUND);
g2.drawChars(startPoint.toCharArray(), 0, startPoint.length(), mouseStartX, mouseStartY - 4);
p = convertPointToLogicalCoord(mouseEndX, mouseEndY);
String endPoint = messageFormat.format(new Object[]{p.getX(), p.getY()});
messageFormat.setFormatByArgumentIndex(0, dateFormat);
messageFormat.setFormatByArgumentIndex(1, PlotConstants.DECIMAL_FORMAT);
g2.setColor(TRANSLUCENT_WHITE);
g2.fillRect(mouseEndX, mouseEndY - fontMetrics.getHeight() - 2, fontMetrics.stringWidth(endPoint), fontMetrics.getHeight());
g2.setColor(END_POINT_FOREGROUND);
g2.drawChars(endPoint.toCharArray(), 0, endPoint.length(), mouseEndX, mouseEndY - 4);
}
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_MarqueeZoomListener.java |
590 | private class MarqueeCanvas extends JPanel {
private MessageFormat messageFormat = new MessageFormat(" (X: {0} Y: {1}) ");
public MarqueeCanvas() {
setOpaque(false);
setBackground(null);
}
@Override
public void paint(Graphics g) {
if (marqueeRect == null) {
super.paint(g);
return;
}
Graphics2D g2 = (Graphics2D) g;
RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setFont(labelFont);
FontMetrics fontMetrics = g2.getFontMetrics();
g2.setRenderingHints(renderHints);
g2.setStroke(new BasicStroke(1f,
BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_MITER,
1f,
new float[]{2f},
0.0f));
g2.setColor(Color.white);
g2.drawRect(marqueeRect.x, marqueeRect.y, marqueeRect.width, marqueeRect.height);
Point2D p = convertPointToLogicalCoord(mouseStartX, mouseStartY);
String startPoint = messageFormat.format(new Object[]{p.getX(), p.getY()});
messageFormat.setFormatByArgumentIndex(0, dateFormat);
messageFormat.setFormatByArgumentIndex(1, PlotConstants.DECIMAL_FORMAT);
g2.setColor(TRANSLUCENT_WHITE);
g2.fillRect(mouseStartX, mouseStartY - fontMetrics.getHeight() - 2, fontMetrics.stringWidth(startPoint), fontMetrics.getHeight());
g2.setColor(START_POINT_FOREGROUND);
g2.drawChars(startPoint.toCharArray(), 0, startPoint.length(), mouseStartX, mouseStartY - 4);
p = convertPointToLogicalCoord(mouseEndX, mouseEndY);
String endPoint = messageFormat.format(new Object[]{p.getX(), p.getY()});
messageFormat.setFormatByArgumentIndex(0, dateFormat);
messageFormat.setFormatByArgumentIndex(1, PlotConstants.DECIMAL_FORMAT);
g2.setColor(TRANSLUCENT_WHITE);
g2.fillRect(mouseEndX, mouseEndY - fontMetrics.getHeight() - 2, fontMetrics.stringWidth(endPoint), fontMetrics.getHeight());
g2.setColor(END_POINT_FOREGROUND);
g2.drawChars(endPoint.toCharArray(), 0, endPoint.length(), mouseEndX, mouseEndY - 4);
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_MarqueeZoomListener.java |
591 | public class PanAndZoomManager {
private final static Logger logger = LoggerFactory.getLogger(PanAndZoomManager.class);
private PlotterPlot plot;
private boolean inZoomMode;
private boolean inPanMode;
public PanAndZoomManager(PlotterPlot quinnCurtisPlot) {
plot = quinnCurtisPlot;
}
public void enteredPanMode() {
logger.debug("Entering pan mode");
inPanMode = true;
// turn off the limit manager.
plot.limitManager.setEnabled(false);
plot.setPlotDisplayState(PlotDisplayState.USER_INTERACTION);
}
public void exitedPanMode() {
inPanMode = false;
logger.debug("Exited pan mode");
}
public void enteredZoomMode() {
logger.debug("Entered zoom mode");
inZoomMode = true;
// turn off the limit manager.
plot.limitManager.setEnabled(false);
plot.setPlotDisplayState(PlotDisplayState.USER_INTERACTION);
}
public void exitedZoomMode() {
inZoomMode = false;
logger.debug("Exited zoom mode");
}
public boolean isInZoomMode() {
return inZoomMode;
}
public boolean isInPanMode() {
return inPanMode;
}
public void panAction(PanDirection panningAction) {
XYAxis xAxis = plot.plotView.getXAxis();
XYAxis yAxis = plot.plotView.getYAxis();
boolean timeChanged = false;
if (plot.axisOrientation == AxisOrientationSetting.X_AXIS_AS_TIME) {
double nonTimeScalePanAmount = yAxis.getEnd() - yAxis.getStart();
double timeScalePanAmount = xAxis.getEnd() - xAxis.getStart();
timeScalePanAmount = (timeScalePanAmount/100) * PlotConstants.PANNING_TIME_AXIS_PERCENTAGE;
nonTimeScalePanAmount= (nonTimeScalePanAmount/100) * PlotConstants.PANNING_TIME_AXIS_PERCENTAGE;
if (panningAction == PanDirection.PAN_HIGHER_Y_AXIS) {
yAxis.shift(nonTimeScalePanAmount);
pinNonTime();
} else if (panningAction == PanDirection.PAN_LOWER_Y_AXIS) {
yAxis.shift(-nonTimeScalePanAmount);
pinNonTime();
} else if (panningAction == PanDirection.PAN_LOWER_X_AXIS) {
xAxis.shift(-timeScalePanAmount);
pinTime();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (panningAction == PanDirection.PAN_HIGHER_X_AXIS) {
xAxis.shift(timeScalePanAmount);
pinTime();
plot.notifyObserversTimeChange();
timeChanged = true;
}
} else {
double nonTimeScalePanAmount = xAxis.getEnd() - xAxis.getStart();
double timeScalePanAmount = yAxis.getEnd() - yAxis.getStart();
timeScalePanAmount = (timeScalePanAmount/100) * PlotConstants.PANNING_TIME_AXIS_PERCENTAGE;
nonTimeScalePanAmount= (nonTimeScalePanAmount/100) * PlotConstants.PANNING_TIME_AXIS_PERCENTAGE;
if (panningAction == PanDirection.PAN_HIGHER_Y_AXIS) {
yAxis.shift(timeScalePanAmount);
pinTime();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (panningAction == PanDirection.PAN_LOWER_Y_AXIS) {
yAxis.shift(-timeScalePanAmount);
pinTime();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (panningAction == PanDirection.PAN_LOWER_X_AXIS) {
xAxis.shift(-nonTimeScalePanAmount);
pinNonTime();
} else if (panningAction == PanDirection.PAN_HIGHER_X_AXIS) {
xAxis.shift(nonTimeScalePanAmount);
pinNonTime();
}
}
plot.plotAbstraction.updateResetButtons();
plot.refreshDisplay();
if(timeChanged) {
plot.clearAllDataFromPlot();
plot.plotAbstraction.requestPlotData(plot.getCurrentTimeAxisMin(), plot.getCurrentTimeAxisMax());
}
}
private void pinTime() {
plot.plotAbstraction.getTimeAxisUserPin().setPinned(true);
}
private void pinNonTime() {
plot.getNonTimeAxisUserPin().setPinned(true);
}
private void markTimeZoomed() {
Axis axis = plot.plotAbstraction.getTimeAxis();
pinTime();
axis.setZoomed(true);
}
private void markNonTimeZoomed() {
Axis axis = plot.getNonTimeAxis();
pinNonTime();
axis.setZoomed(true);
}
public void zoomAction(ZoomDirection zoomAction) {
XYAxis xAxis = plot.plotView.getXAxis();
XYAxis yAxis = plot.plotView.getYAxis();
boolean timeChanged = false;
if (plot.axisOrientation == AxisOrientationSetting.X_AXIS_AS_TIME) {
double nonTimeScaleZoomAmount = yAxis.getEnd() - yAxis.getStart();
double timeScaleZoomAmount = xAxis.getEnd() - xAxis.getStart();
timeScaleZoomAmount = (timeScaleZoomAmount/100) * PlotConstants.ZOOMING_TIME_AXIS_PERCENTAGE;
nonTimeScaleZoomAmount= (nonTimeScaleZoomAmount/100) * PlotConstants.ZOOMING_TIME_AXIS_PERCENTAGE;
if (zoomAction == ZoomDirection.ZOOM_IN_HIGH_Y_AXIS) {
yAxis.setEnd(yAxis.getEnd() - nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_OUT_HIGH_Y_AXIS) {
yAxis.setEnd(yAxis.getEnd() + nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_IN_CENTER_Y_AXIS) {
yAxis.setStart(yAxis.getStart() + nonTimeScaleZoomAmount);
yAxis.setEnd(yAxis.getEnd() - nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_OUT_CENTER_Y_AXIS) {
yAxis.setStart(yAxis.getStart() - nonTimeScaleZoomAmount);
yAxis.setEnd(yAxis.getEnd() + nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_IN_LOW_Y_AXIS) {
yAxis.setStart(yAxis.getStart() + nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_OUT_LOW_Y_AXIS) {
yAxis.setStart(yAxis.getStart() - nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_IN_LEFT_X_AXIS) {
xAxis.setStart(xAxis.getStart() + timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_OUT_LEFT_X_AXIS) {
xAxis.setStart(xAxis.getStart() - timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_IN_CENTER_X_AXIS) {
xAxis.setStart(xAxis.getStart() + timeScaleZoomAmount);
xAxis.setEnd(xAxis.getEnd() - timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_OUT_CENTER_X_AXIS) {
xAxis.setStart(xAxis.getStart() - timeScaleZoomAmount);
xAxis.setEnd(xAxis.getEnd() + timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_IN_RIGHT_X_AXIS) {
xAxis.setEnd(xAxis.getEnd() - timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_OUT_RIGHT_X_AXIS) {
xAxis.setEnd(xAxis.getEnd() + timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
}
} else {
double nonTimeScaleZoomAmount = xAxis.getEnd() - xAxis.getStart();
double timeScaleZoomAmount = yAxis.getEnd() - yAxis.getStart();
timeScaleZoomAmount = (timeScaleZoomAmount/100) * PlotConstants.ZOOMING_TIME_AXIS_PERCENTAGE;
nonTimeScaleZoomAmount = (nonTimeScaleZoomAmount/100) * PlotConstants.ZOOMING_TIME_AXIS_PERCENTAGE;
if (zoomAction == ZoomDirection.ZOOM_IN_HIGH_Y_AXIS) {
yAxis.setEnd(yAxis.getEnd() - timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_OUT_HIGH_Y_AXIS) {
yAxis.setEnd(yAxis.getEnd() + timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_IN_CENTER_Y_AXIS) {
yAxis.setStart(yAxis.getStart() + timeScaleZoomAmount);
yAxis.setEnd(yAxis.getEnd() - timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_OUT_CENTER_Y_AXIS) {
yAxis.setStart(yAxis.getStart() - timeScaleZoomAmount);
yAxis.setEnd(yAxis.getEnd() + timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_IN_LOW_Y_AXIS) {
yAxis.setStart(yAxis.getStart() + timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_OUT_LOW_Y_AXIS) {
yAxis.setStart(yAxis.getStart() - timeScaleZoomAmount);
markTimeZoomed();
plot.notifyObserversTimeChange();
timeChanged = true;
} else if (zoomAction == ZoomDirection.ZOOM_IN_LEFT_X_AXIS) {
xAxis.setStart(xAxis.getStart() + nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_OUT_LEFT_X_AXIS) {
xAxis.setStart(xAxis.getStart() - nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_IN_CENTER_X_AXIS) {
xAxis.setStart(xAxis.getStart() + nonTimeScaleZoomAmount);
xAxis.setEnd(xAxis.getEnd() - nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_OUT_CENTER_X_AXIS) {
xAxis.setStart(xAxis.getStart() - nonTimeScaleZoomAmount);
xAxis.setEnd(xAxis.getEnd() + nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_IN_RIGHT_X_AXIS) {
xAxis.setEnd(xAxis.getEnd() - nonTimeScaleZoomAmount);
markNonTimeZoomed();
} else if (zoomAction == ZoomDirection.ZOOM_OUT_RIGHT_X_AXIS) {
xAxis.setEnd(xAxis.getEnd() + nonTimeScaleZoomAmount);
markNonTimeZoomed();
}
}
plot.plotAbstraction.updateResetButtons();
plot.refreshDisplay();
if(timeChanged) {
plot.plotDataManager.resizeAndReloadPlotBuffer();
}
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PanAndZoomManager.java |
592 | public interface PlotAbstraction extends PlotObserver {
/**
* Get instance of the plot wrapped in a JFrame.
* @return the plot wrapped in a JFrame.
*/
public JPanel getPlotPanel();
/**
* Add a data set to the plot.
*
* The dataset must not have already been added to the plot.
*
* @param dataSetName unique name of the data set.
*/
public void addDataSet(String dataSetName);
/**
* Add a dataset to the plot.
*
* @param dataSetName unique name of the data set.
* @param plottingColor desired plotting color of data set.
*/
public void addDataSet(String dataSetName, Color plottingColor);
/**
* Add a dataset to the plot.
*
* @param dataSetName unique name of the data set.
* @param displayName the base display name for the data set.
*/
public void addDataSet(String dataSetName, String displayName);
/**
* Adds the data per feed Id, timestamp and telemetry value.
* @param feedID - feed Id.
* @param time - timestamp.
* @param value - telemetry value.
*/
public void addData(String feedID, long time, double value);
/**
* Determine if data set is defined in plot.
* @param setName the dataset name
* @return true if the dataset is defined in the plot, false otherwise.
*/
public boolean isKnownDataSet(String setName);
/**
* Instruct the plot to redraw.
*/
public void refreshDisplay();
/**
* Update the legend entry for the corresponding data set.
* @param dataSetName the unique name of the data set
* @param info the rendering information
*/
void updateLegend(String dataSetName, FeedProvider.RenderingInfo info);
/**
* Return the state of the alarm which indicates if plot has experienced data which is outside
* of its current non time max axis limit.
* @return limit alarm state maximum.
*/
public LimitAlarmState getNonTimeMaxAlarmState(int subGroupIndex);
/**
* Return the state of the alarm which indicates if plot has experienced data which is outside
* of its current non time min axis limit.
* @return limit alarm state minimal.
*/
public LimitAlarmState getNonTimeMinAlarmState(int subGroupIndex);
/**
* Return the minimum time currently displayed on the time axis.
* @return Gregorian calendar for minimal time.
*/
public GregorianCalendar getMinTime();
/**
* Return the maximum time currently displayed on the time axis.
* @return Gregorian calendar for maximum time.
*/
public GregorianCalendar getMaxTime();
/**
* Return the time axis setting which indicates if time is on the x or y axis.
* @return axis orientation setting.
*/
public AxisOrientationSetting getAxisOrientationSetting();
/**
* Return the x-axis maximum location which indicates if the maximum is on the left or right end of this axis.
* @return x-axis maximum location setting.
*/
public XAxisMaximumLocationSetting getXAxisMaximumLocation();
/**
* Return the y-axis maximum location which indicates if the maximum is at the top or bottom of this axis.
* @return y-axis maximum location setting.
*/
public YAxisMaximumLocationSetting getYAxisMaximumLocation();
/**
* Return whether the ordinal position of each collection should be used to group stacked plots.
* @return true if ordinal position should be used, false if the collection contents should be used.
*/
public boolean useOrdinalPositionForSubplots();
/**
* Return the plot's mode when data exceeds the current span of the time axis.
* @return time axis subsequent bounds setting.
*/
public TimeAxisSubsequentBoundsSetting getTimeAxisSubsequentSetting();
/**
* Return the plot's mode when data exceeds the current minimum bound of the non time axis.
* @return non-time axis subsequent bounds settings minimal.
*/
public NonTimeAxisSubsequentBoundsSetting getNonTimeAxisSubsequentMinSetting();
/**
* Return the plot's mode when data exceeds the current maximum bound of the non time axis.
* @return non-time axis subsequent bounds settings maximum.
*/
public NonTimeAxisSubsequentBoundsSetting getNonTimeAxisSubsequentMaxSetting();
/**
* Return the value specified initially as the non time axis minimum bound.
* @return non-time minimal.
*/
public double getNonTimeMin();
/**
* Return the value specified initially as the non time axis maximum bound.
* @return non-time maximum.
*/
public double getNonTimeMax();
/**
* Return the value specified initially as the time axis minimum bound.
* @return time minimal.
*/
public long getTimeMin();
/**
* Return the value specified initially as the time axis maximum bound.
* @return time maximum.
*/
public long getTimeMax();
/**
* Return the percentage padding to apply when expanding the time axis.
* @return time padding.
*/
public double getTimePadding();
/**
* Return the percentage padding to apply when expanding the non time axis minimum bound.
* @return non-time minimal padding.
*/
public double getNonTimeMinPadding();
/**
* Return the percentage padding to apply when expanding the non time axis minimum bound.
* @return non-time maximum padding.
*/
public double getNonTimeMaxPadding();
/**
* Instruct the plot to show a time sync line.
* @param time at which to show the time sync line.
*/
public void showTimeSyncLine(GregorianCalendar time);
/**
* Instruct the plot to remove any time sync line currently being displayed.
*/
public void removeTimeSyncLine();
/**
* Return true if the time sync line is visible. False otherwise.
* @return boolean flag is time sync line visible.
*/
public boolean isTimeSyncLineVisible();
/**
* Initialize time Synchronization mode.
* @param time time at which to synchronize.
*/
public void initiateGlobalTimeSync(GregorianCalendar time);
/**
* Updates the synchronization time.
* @param time new time to synchronize on.
*/
public void updateGlobalTimeSync(GregorianCalendar time);
/**
* Notify plot manager that synchronization mode has terminated.
*/
public void notifyGlobalTimeSyncFinished();
/**
* Return true if the plot is in time sync mode, false otherwise.
* @return true if in time sync mode; false otherwise.
*/
public boolean inTimeSyncMode();
/**
* Return the largest value shown on the non-time axis currently visible on the plot.
* @return non-time maximum currently displayed.
*/
public double getNonTimeMaxCurrentlyDisplayed();
/**
* Return the smallest value shown on the non-time axis currently visible on the plot.
* @return non-time minimal currently displayed.
*/
public double getNonTimeMinCurrentlyDisplayed();
/**
* Return the underlying plotting package. This method is only to be used for testing.
* @return the underlying plotting package.
*/
AbstractPlottingPackage returnPlottingPackage();
/**
* Enable or disable plot data compression.
* @param compression enabled flag.
*/
public void setCompressionEnabled(boolean compression);
/**
* Return true if plot data compression is enabled, false otherwise.
* @return true if compression is enabled; false otherwise.
*/
public boolean isCompresionEnabled();
/**
* Allows the plot package to request a data refresh at the given compression ratio.
* @param startTime of data requested.
* @param endTime of data requested.
*/
void requestPlotData(GregorianCalendar startTime,GregorianCalendar endTime);
/**
* Inform the plot that a data buffer update event has started.
*/
public void informUpdateDataEventStarted();
/**
* Inform the plot that a data buffer update event has finished.
*/
public void informUpdateDataEventCompleted();
/**
* Inform the plot that a regular data stream update event has started.
*/
public void informUpdateFromFeedEventStarted();
/**
* Inform the plot that a regular data stream update event has ended.
*/
public void informUpdateFromFeedEventCompleted();
/**
* Returns the current MCT time.
* @return the current MCT time in UNIX timestamp.
*/
public long getCurrentMCTTime();
/**
* Return true if plot matches settings, false otherwise.
* @param settings the plot settings.
* @return true if plot matches the settings; false otherwise.
*/
public boolean plotMatchesSetting(PlotSettings settings);
/**
* Hold the settings for a plot.
*/
public class PlotSettings {
/** Time axis orientation setting. */
public AxisOrientationSetting timeAxisSetting = null;
/** X-axis maximum location setting. */
public XAxisMaximumLocationSetting xAxisMaximumLocation = null;
/** Y-axis maximum location setting. */
public YAxisMaximumLocationSetting yAxisMaximumLocation = null;
/** Time axis subsequent bounds settings. */
public TimeAxisSubsequentBoundsSetting timeAxisSubsequent = null;
/** Non-time axis minimal subsequent bounds setting. */
public NonTimeAxisSubsequentBoundsSetting nonTimeAxisSubsequentMinSetting = null;
/** Non-time axis maximum subsequent bounds setting. */
public NonTimeAxisSubsequentBoundsSetting nonTimeAxisSubsequentMaxSetting = null;
/** Max time in millisecs. */
public long maxTime = 0;
/** Min time in millisecs. */
public long minTime = 0;
/** Max non-time value. */
public double maxNonTime = 0;
/** Min non-time value. */
public double minNonTime = 0;
/** Time padding value. */
public double timePadding = 0;
/** Non-time max padding. */
public double nonTimeMaxPadding = 0;
/** Non-time min padding. */
public double nonTimeMinPadding = 0;
/** Ordinal position for stacked plots. Defaults to true. */
public boolean ordinalPositionForStackedPlots = true;
/** Pin time axis. Defaults to false. */
public boolean pinTimeAxis = false;
/** Plot line drawing type; line, markers, or both. */
public PlotLineDrawingFlags plotLineDraw = null;
/** Plot line connection style; direct or step. */
public PlotLineConnectionType plotLineConnectionType = null;
/**
* Checks for time axis orientation setting null.
* @return time axis orientation setting null check.
*/
public boolean isNull() {
return timeAxisSetting == null;
}
}
/**
* Contains settings for specific lines on a plot.
*/
public class LineSettings {
private String identifier = "";
private Integer colorIndex = 0;
private Integer thickness = 1;
private Integer marker = 0;
private String character = "";
private boolean useCharacter = false;
private boolean hasRegression = false;
private Integer regressionPoints = PlotConstants.NUMBER_REGRESSION_POINTS;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public Integer getColorIndex() {
return colorIndex;
}
public void setColorIndex(Integer colorIndex) {
this.colorIndex = colorIndex;
}
public Integer getThickness() {
return thickness;
}
public void setThickness(Integer thickness) {
this.thickness = thickness;
}
public Integer getMarker() {
return marker;
}
public void setMarker(Integer marker) {
this.marker = marker;
}
public String getCharacter() {
return character;
}
public void setCharacter(String character) {
this.character = character;
}
public boolean getUseCharacter() {
return useCharacter;
}
public void setUseCharacter(boolean useCharacter) {
this.useCharacter = useCharacter;
}
public boolean getHasRegression() {
return hasRegression;
}
public void setHasRegression(boolean hasRegression) {
this.hasRegression = hasRegression;
}
public Integer getRegressionPoints() {
return regressionPoints;
}
public void setRegressionPoints(Integer regressionPoints) {
this.regressionPoints = regressionPoints;
}
}
/**
* Instruct plot to remove all its current data.
*/
void clearAllDataFromPlot();
/**
* Creates a new pin for this plot.
* The plot is pinned if any of its pins are pinned.
* @return new pin.
*/
public Pinnable createPin();
/**
* Returns the user pin for the time axis.
* This is a special pin that the user uses to manually pin the time axis.
* @return manual time axis pin.
*/
public Pinnable getTimeAxisUserPin();
/**
* Returns true if the plot is pinned.
* The plot is pinned if any of its pins are pinned.
* @return true if the plot is pinned.
*/
boolean isPinned();
/**
* Returns a list of sub plots on this plot.
* The returned list may not be modifiable.
* @return sub plots.
*/
public List<AbstractPlottingPackage> getSubPlots();
/**
* Returns the time axis.
* @return the time axis.
*/
public Axis getTimeAxis();
/**
* Updates the visibility of the corner reset buttons based on which axes are pinned and what data is visible.
*/
public void updateResetButtons();
/**
* Sets the X-Y time axis.
* @param axis X-Y time axis
*/
public void setPlotTimeAxis(TimeXYAxis axis);
/**
* Get the drawing mode (lines, markers, both) associated with this plot.
* @return the drawing mode
*/
public PlotLineDrawingFlags getPlotLineDraw();
/**
* Get the connection type (direct, or some form of step) used to connect
* data points on a plot.
* @return the method for connecting points on this plot
*/
public PlotLineConnectionType getPlotLineConnectionType();
/**
* Set the drawing mode (lines, markers, both) for this plot
* @param draw the drawing mode
*/
public void setPlotLineDraw(PlotLineDrawingFlags draw);
/**
* Set the line connection type (direct, or some form of step) used to
* connect data point on this plot.
* @param type the method for connecting points on this plot
*/
public void setPlotLineConnectionType(PlotLineConnectionType type);
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PlotAbstraction.java |
593 | public class LineSettings {
private String identifier = "";
private Integer colorIndex = 0;
private Integer thickness = 1;
private Integer marker = 0;
private String character = "";
private boolean useCharacter = false;
private boolean hasRegression = false;
private Integer regressionPoints = PlotConstants.NUMBER_REGRESSION_POINTS;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public Integer getColorIndex() {
return colorIndex;
}
public void setColorIndex(Integer colorIndex) {
this.colorIndex = colorIndex;
}
public Integer getThickness() {
return thickness;
}
public void setThickness(Integer thickness) {
this.thickness = thickness;
}
public Integer getMarker() {
return marker;
}
public void setMarker(Integer marker) {
this.marker = marker;
}
public String getCharacter() {
return character;
}
public void setCharacter(String character) {
this.character = character;
}
public boolean getUseCharacter() {
return useCharacter;
}
public void setUseCharacter(boolean useCharacter) {
this.useCharacter = useCharacter;
}
public boolean getHasRegression() {
return hasRegression;
}
public void setHasRegression(boolean hasRegression) {
this.hasRegression = hasRegression;
}
public Integer getRegressionPoints() {
return regressionPoints;
}
public void setRegressionPoints(Integer regressionPoints) {
this.regressionPoints = regressionPoints;
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PlotAbstraction.java |
594 | public class PlotSettings {
/** Time axis orientation setting. */
public AxisOrientationSetting timeAxisSetting = null;
/** X-axis maximum location setting. */
public XAxisMaximumLocationSetting xAxisMaximumLocation = null;
/** Y-axis maximum location setting. */
public YAxisMaximumLocationSetting yAxisMaximumLocation = null;
/** Time axis subsequent bounds settings. */
public TimeAxisSubsequentBoundsSetting timeAxisSubsequent = null;
/** Non-time axis minimal subsequent bounds setting. */
public NonTimeAxisSubsequentBoundsSetting nonTimeAxisSubsequentMinSetting = null;
/** Non-time axis maximum subsequent bounds setting. */
public NonTimeAxisSubsequentBoundsSetting nonTimeAxisSubsequentMaxSetting = null;
/** Max time in millisecs. */
public long maxTime = 0;
/** Min time in millisecs. */
public long minTime = 0;
/** Max non-time value. */
public double maxNonTime = 0;
/** Min non-time value. */
public double minNonTime = 0;
/** Time padding value. */
public double timePadding = 0;
/** Non-time max padding. */
public double nonTimeMaxPadding = 0;
/** Non-time min padding. */
public double nonTimeMinPadding = 0;
/** Ordinal position for stacked plots. Defaults to true. */
public boolean ordinalPositionForStackedPlots = true;
/** Pin time axis. Defaults to false. */
public boolean pinTimeAxis = false;
/** Plot line drawing type; line, markers, or both. */
public PlotLineDrawingFlags plotLineDraw = null;
/** Plot line connection style; direct or step. */
public PlotLineConnectionType plotLineConnectionType = null;
/**
* Checks for time axis orientation setting null.
* @return time axis orientation setting null check.
*/
public boolean isNull() {
return timeAxisSetting == null;
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PlotAbstraction.java |
595 | public class PlotConstants {
/*
* Default Plot Properties.
*/
public static final int DEFAULT_NUMBER_OF_SUBPLOTS = 1;
public static final boolean LOCAL_CONTROLS_ENABLED_BY_DEFAULT = true;
public static final YAxisMaximumLocationSetting DEFAULT_Y_AXIS_MAX_LOCATION_SETTING = YAxisMaximumLocationSetting.MAXIMUM_AT_TOP;
public static final NonTimeAxisSubsequentBoundsSetting DEFAULT_NON_TIME_AXIS_MIN_SUBSEQUENT_SETTING = NonTimeAxisSubsequentBoundsSetting.SEMI_FIXED;
public static final NonTimeAxisSubsequentBoundsSetting DEFAULT_NON_TIME_AXIS_MAX_SUBSEQUENT_SETTING = NonTimeAxisSubsequentBoundsSetting.SEMI_FIXED;
public static final int MILLISECONDS_IN_SECOND = 1000;
public static final int MILLISECONDS_IN_MIN = MILLISECONDS_IN_SECOND * 60;
public static final int MILLISECONDS_IN_HOUR = MILLISECONDS_IN_MIN * 60;
public static final int MILLISECONDS_IN_DAY = MILLISECONDS_IN_HOUR * 24;
public static final int DEFAUlT_PLOT_SPAN = 30 * 60 * 1000; // 30 mins in Milliseconds
public static final Color ROLL_OVER_PLOT_LINE_COLOR = Color.white;
public static final int DEFAULT_TIME_AXIS_FONT_SIZE = 10;
public static final Font DEFAULT_TIME_AXIS_FONT = new Font("Arial", Font.PLAIN, DEFAULT_TIME_AXIS_FONT_SIZE);
public static final int DEFAULT_PLOTLINE_THICKNESS = 1;
public static final int SELECTED_LINE_THICKNESS = 2;
public static final Color DEFAULT_PLOT_FRAME_BACKGROUND_COLOR = new Color(51, 51, 51);
public static final Color DEFAULT_PLOT_AREA_BACKGROUND_COLOR = Color.black;
public static final int DEFAULT_TIME_AXIS_INTERCEPT = 0;
public static final Color DEFAULT_TIME_AXIS_COLOR = Color.white;
public static final Color DEFAULT_TIME_AXIS_LABEL_COLOR = Color.white;
public static final Color DEFAULT_NON_TIME_AXIS_COLOR= Color.white;
public static final Color DEFAULT_GRID_LINE_COLOR = Color.LIGHT_GRAY;
public static final int DEFAULT_MIN_SAMPLES_FOR_AUTO_SCALE = 0;
public static final double DEFAULT_TIME_AXIS_PADDING = 0.25;
public static final double DEFAULT_TIME_AXIS_PADDING_JUMP_MIN = 0.05;
public static final double DEFAULT_TIME_AXIS_PADDING_JUMP_MAX = 0.25;
public static final double DEFAULT_TIME_AXIS_PADDING_SCRUNCH_MIN = 0.20;
public static final double DEFAULT_TIME_AXIS_PADDING_SCRUNCH_MAX = 0.25;
public static final double DEFAULT_NON_TIME_AXIS_PADDING_MAX = 0.05;
public static final double DEFAULT_NON_TIME_AXIS_PADDING_MIN = 0.05;
public static final double DEFAULT_NON_TIME_AXIS_MIN_VALUE = 0;
public static final double DEFAULT_NON_TIME_AXIS_MAX_VALUE = 1;
public static final long DEFAULT_TIME_AXIS_MIN_VALUE = new GregorianCalendar().getTimeInMillis();
public static final long DEFAULT_TIME_AXIS_MAX_VALUE= DEFAULT_TIME_AXIS_MIN_VALUE + DEFAUlT_PLOT_SPAN;
public static final int MAX_NUMBER_OF_DATA_ITEMS_ON_A_PLOT = 30;
public static final int MAX_NUMBER_SUBPLOTS = 10;
public static final PlotLineDrawingFlags DEFAULT_PLOT_LINE_DRAW = new PlotLineDrawingFlags(true, false);
public static final int MAJOR_TICK_MARK_LENGTH = 3;
public static final int MINOR_TICK_MARK_LENGTH = 1;
public static final String GMT = "GMT";
public static final String DEFAULT_TIME_ZONE = GMT;
public static final String DEFAULT_TIME_AXIS_DATA_FORMAT = "DDD/HH:mm:ss"; // add a z to see the time zone.
// Field names for persistence
public static final String TIME_AXIS_SETTING = "PlotTimeAxisSetting";
public static final String X_AXIS_MAXIMUM_LOCATION_SETTING = "PlotXAxisMaximumLocation";
public static final String Y_AXIS_MAXIMUM_LOCATION_SETTING = "PlotYAxisMaximumLocation";
public static final String TIME_AXIS_SUBSEQUENT_SETTING = "PlotTimeAxisSubsequentSetting";
public static final String NON_TIME_AXIS_SUBSEQUENT_MIN_SETTING = "PlotNonTimeAxisSubsequentMinSetting";
public static final String NON_TIME_AXIS_SUBSEQUENT_MAX_SETTING = "PlotNonTimeAxisSubsequentMaxSetting";
public static final String NON_TIME_MAX = "NonTimeMax";
public static final String NON_TIME_MIN = "NonTimeMin";
public static final String TIME_MAX = "TimeMax";
public static final String TIME_MIN = "TimeMin";
public static final String TIME_PADDING = "TimePadding";
public static final String NON_TIME_MIN_PADDING = "NonTimeMinPadding";
public static final String NON_TIME_MAX_PADDING = "NonTimeMaxPadding";
public static final String GROUP_BY_ORDINAL_POSITION = "GroupByOrdinalPosition";
public static final String PIN_TIME_AXIS = "PinTimeAxis";
public static final String DRAW_LINES = "PlotLineDrawLines";
public static final String DRAW_MARKERS = "PlotLineDrawMarkers";
public static final String DRAW_CHARACTERS = "PlotLineDrawCharacters";
public static final String CONNECTION_TYPE = "PlotLineConnectionType";
public static final String COLOR_ASSIGNMENTS = "PlotColorAssignments";
public static final String LINE_SETTINGS = "PlotLineSettings";
// Delay before firing a request for data at a higher resolution on a window.
public final static int RESIZE_TIMER = 200; // in milliseconds.
// Limit button border settings
public static final int ARROW_BUTTON_BORDER_STYLE_TOP = 1;
public static final int ARROW_BUTTON_BORDER_STYLE_LEFT = 0;
public static final int ARROW_BUTTON_BORDER_STYLE_BOTTOM = 0;
public static final int ARROW_BUTTON_BORDER_STYLE_RIGHT = 0;
// The size below which the plot will not go before it starts to truncate the legends.
public static final int MINIMUM_PLOT_WIDTH = 200; //200;
public static final int MINIMUM_PLOT_HEIGHT = 100;
public static final int Y_AXIS_WHEN_NON_TIME_LABEL_WIDTH = 28;
// Legends
public final static Color LEGEND_BACKGROUND_COLOR = DEFAULT_PLOT_FRAME_BACKGROUND_COLOR;
public static final int PLOT_LEGEND_BUFFER = 5;
public static final int PLOT_LEGEND_WIDTH = 120;
public static final int PLOT_MINIMUM_LEGEND_WIDTH = 40;
public static final int PLOT_LEGEND_OFFSET_FROM_LEFT_HAND_SIDE = 0;
public static final String LEGEND_NEWLINE_CHARACTER = "\n";
public static final String LEGEND_ELLIPSES = "...";
public static final int MAXIMUM_LEGEND_TEXT_SIZE = 20; //maximum width of a legend
public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#0.000");
// Sync line
public static final Color TIME_SYNC_LINE_COLOR = Color.orange;
public static final int TIME_SYNC_LINE_WIDTH = 2;
public static final int SYNC_LINE_STYLE = 9; // ChartConstants.LS_DASH_DOT;
public static final int SHIFT_KEY_MASK = InputEvent.SHIFT_MASK;
public static final int ALT_KEY_MASK = InputEvent.ALT_MASK;
public static final int CTL_KEY_MASK = InputEvent.CTRL_MASK;
// Data Cursor
public static final Color DATA_CURSOR_COLOR = new Color(235, 235, 235);//new Color(51, 102, 153);
public static final int SLOPE_LINE_STYLE = 0; // ChartConstants.LS_SOLID;
public static final int SLOPE_LINE_WIDTH = 1;
public static final String SLOPE_UNIT = "/min";
public static final String REGRESSION_LINE = "RegressionLine";
public static final int NUMBER_REGRESSION_POINTS = 20;
public static final int SLOPE_UNIT_DIVIDER_IN_MS = PlotConstants.MILLISECONDS_IN_MIN; // per second.
public final static float dash1[] = {10.0f};
// Data Compression
// Sets the default value for data compression which can be overridden by the client.
public static final boolean COMPRESSION_ENABLED_BY_DEFAULT = true;
public static final int MAXIMUM_PLOT_DATA_BUFFER_SLIZE_REQUEST_SIZE = 12 * MILLISECONDS_IN_HOUR ;
// Panning and zooming controls
public static final double PANNING_NON_TIME_AXIS_PERCENTAGE = 25;
public static final double PANNING_TIME_AXIS_PERCENTAGE = 25;
public static final double ZOOMING_NON_TIME_AXIS_PERCENTAGE = 10;
public static final double ZOOMING_TIME_AXIS_PERCENTAGE = 10;
public static final int zoomingTimeAxisIncrementInMiliseconds = 30 * MILLISECONDS_IN_SECOND;
public static final int zoomingNonTimeAxisIncrement = 10;
public static final int LOCAL_CONTROL_HEIGHT = 25;
public static final int LOCAL_CONTROL_WIDTH = 28;
/**
* Orientation of the time axis.
*/
public enum AxisOrientationSetting {
X_AXIS_AS_TIME, Y_AXIS_AS_TIME
}
public enum AxisBounds {
MAX, MIN
}
public enum XAxisMaximumLocationSetting {
MAXIMUM_AT_RIGHT, MAXIMUM_AT_LEFT
}
public enum YAxisMaximumLocationSetting {
MAXIMUM_AT_TOP, MAXIMUM_AT_BOTTOM
}
/**
* Subsequent modes on the time axis.
*/
public enum TimeAxisSubsequentBoundsSetting {
JUMP, SCRUNCH
}
/**
* Subsequent modes on the non-time axis
*/
public enum NonTimeAxisSubsequentBoundsSetting {
AUTO, FIXED, SEMI_FIXED
}
/**
* State that limit alarms can be in.
*/
public enum LimitAlarmState{
NO_ALARM, ALARM_RAISED, ALARM_OPENED_BY_USER, ALARM_CLOSED_BY_USER
}
/**
* Panning actions
*/
public enum PanDirection {
PAN_LOWER_X_AXIS, PAN_HIGHER_X_AXIS, PAN_LOWER_Y_AXIS, PAN_HIGHER_Y_AXIS;
}
/**
* Zoom actions
*/
public enum ZoomDirection {
ZOOM_IN_HIGH_Y_AXIS, ZOOM_OUT_HIGH_Y_AXIS,
ZOOM_IN_CENTER_Y_AXIS, ZOOM_OUT_CENTER_Y_AXIS,
ZOOM_IN_LOW_Y_AXIS, ZOOM_OUT_LOW_Y_AXIS,
ZOOM_IN_LEFT_X_AXIS, ZOOM_OUT_LEFT_X_AXIS,
ZOOM_IN_CENTER_X_AXIS, ZOOM_OUT_CENTER_X_AXIS,
ZOOM_IN_RIGHT_X_AXIS, ZOOM_OUT_RIGHT_X_AXIS;
}
public enum AxisType {
TIME_IN_JUMP_MODE (DEFAULT_TIME_AXIS_PADDING_JUMP_MIN,
DEFAULT_TIME_AXIS_PADDING_JUMP_MAX),
TIME_IN_SCRUNCH_MODE (DEFAULT_TIME_AXIS_PADDING_SCRUNCH_MIN,
DEFAULT_TIME_AXIS_PADDING_SCRUNCH_MAX),
NON_TIME (DEFAULT_NON_TIME_AXIS_PADDING_MIN,
DEFAULT_NON_TIME_AXIS_PADDING_MAX);
private final double minimumDefaultPadding;
private final double maximumDefaultPadding;
AxisType(double minPadding, double maxPadding) {
this.minimumDefaultPadding = minPadding;
this.maximumDefaultPadding = maxPadding;
}
public double getMinimumDefaultPadding() {
return minimumDefaultPadding;
}
public String getMinimumDefaultPaddingAsText() {
String percentString = NumberFormat.getPercentInstance().format(this.minimumDefaultPadding);
return percentString.substring(0, percentString.length()-1);
}
public double getMaximumDefaultPadding() {
return maximumDefaultPadding;
}
public String getMaximumDefaultPaddingAsText() {
String percentString = NumberFormat.getPercentInstance().format(this.maximumDefaultPadding);
return percentString.substring(0, percentString.length()-1);
}
}
/**
* DISPLAY_ONLY optimizes the plot buffering for displaying multiple plots with the minimum buffer wait.
* Switching to USER_INTERACTION mode deepens and widens the plot buffer to support user interactions such
* as panning and zooming.
*/
public enum PlotDisplayState {
DISPLAY_ONLY, USER_INTERACTION;
}
/**
* Indicates whether we will be drawing plot lines, point markers, or both.
*/
public static class PlotLineDrawingFlags {
private boolean line, markers;
public PlotLineDrawingFlags(boolean line, boolean markers) {
this.line = line;
this.markers = markers;
}
public boolean drawLine() {
return line;
}
public boolean drawMarkers() {
return markers;
}
}
/**
* Indicates how to connect plot point with lines.
*/
public enum PlotLineConnectionType {
DIRECT, STEP_X_THEN_Y
}
/**
* Params for Labeling Algorithm
*/
/**
* The regular expression defining the delimiter pattern between words.
* Words are delimited by a sequence of one or more spaces or underscores.
*/
public static final String WORD_DELIMITERS = "[ _]+";
/**
* The compiled regular expression defining the delimiter pattern between
* words.
*/
public static final Pattern WORD_DELIMITER_PATTERN = Pattern.compile(WORD_DELIMITERS);
/**
* The separator to use when concatenating words together to form labels.
*/
public static final String WORD_SEPARATOR = " ";
/**
* The maximum thickness for a plot line's stroke
*/
public static final int MAX_LINE_THICKNESS = 5;
} | true | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PlotConstants.java |
596 | public enum AxisBounds {
MAX, MIN
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PlotConstants.java |
597 | public enum AxisOrientationSetting {
X_AXIS_AS_TIME, Y_AXIS_AS_TIME
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PlotConstants.java |
598 | public enum AxisType {
TIME_IN_JUMP_MODE (DEFAULT_TIME_AXIS_PADDING_JUMP_MIN,
DEFAULT_TIME_AXIS_PADDING_JUMP_MAX),
TIME_IN_SCRUNCH_MODE (DEFAULT_TIME_AXIS_PADDING_SCRUNCH_MIN,
DEFAULT_TIME_AXIS_PADDING_SCRUNCH_MAX),
NON_TIME (DEFAULT_NON_TIME_AXIS_PADDING_MIN,
DEFAULT_NON_TIME_AXIS_PADDING_MAX);
private final double minimumDefaultPadding;
private final double maximumDefaultPadding;
AxisType(double minPadding, double maxPadding) {
this.minimumDefaultPadding = minPadding;
this.maximumDefaultPadding = maxPadding;
}
public double getMinimumDefaultPadding() {
return minimumDefaultPadding;
}
public String getMinimumDefaultPaddingAsText() {
String percentString = NumberFormat.getPercentInstance().format(this.minimumDefaultPadding);
return percentString.substring(0, percentString.length()-1);
}
public double getMaximumDefaultPadding() {
return maximumDefaultPadding;
}
public String getMaximumDefaultPaddingAsText() {
String percentString = NumberFormat.getPercentInstance().format(this.maximumDefaultPadding);
return percentString.substring(0, percentString.length()-1);
}
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PlotConstants.java |
599 | public enum LimitAlarmState{
NO_ALARM, ALARM_RAISED, ALARM_OPENED_BY_USER, ALARM_CLOSED_BY_USER
} | false | fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PlotConstants.java |