Unnamed: 0
int64 0
2.05k
| func
stringlengths 27
124k
| target
bool 2
classes | project
stringlengths 39
117
|
---|---|---|---|
900 | public class GraphicalManifestation extends FeedView implements RenderingCallback {
private static ResourceBundle bundle = ResourceBundle.getBundle("GraphicsResourceBundle");
private static final long serialVersionUID = -5934962679343158613L;
private final List<FeedProvider> feedProviderList;
private GraphicalSettings settings;
private List<Brush> layers;
private Shape shape;
public static final String VIEW_ROLE_NAME = bundle.getString("View_Name");
public GraphicalManifestation(AbstractComponent component, ViewInfo vi) {
super(component,vi);
layers = new ArrayList<Brush>();
settings = new GraphicalSettings(this);
setBackground(UIManager.getColor("background"));
this.setOpaque(true);
feedProviderList = Collections.singletonList(getFeedProvider(getManifestedComponent()));
buildFromSettings();
}
@Override
protected JComponent initializeControlManifestation() {
return new JScrollPane(new GraphicalControlPanel(this),
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
@Override
public void paint(Graphics g) {
boolean hasTitle = true;
NamingContext nc = getNamingContext();
if (nc != null && nc.getContextualName() == null) hasTitle = false;
/* Only paint background if we are on a panel or similar */
if (hasTitle) super.paint(g);
/* Pad for border, or other stuff */
Rectangle bounds = getBounds().getBounds();
int padding = Math.min(bounds.width, bounds.height) / 20;
bounds.grow(-padding, -padding);
/* Paint all layers in order */
for (Brush b : layers) {
b.draw(shape, g, bounds);
}
if (!hasTitle) paintDisplayName(g);
}
private void paintDisplayName(Graphics g) {
g.setFont(g.getFont().deriveFont(9.0f));
String name = getManifestedComponent().getDisplayName();
int width = g.getFontMetrics().stringWidth(name);
int height = g.getFontMetrics().getAscent() - 2;
int x = (getBounds().width - width) / 2;
int y = (getBounds().height) - height * 2;
g.setColor(new Color(255,255,255,160));
g.fillRoundRect(x - 4, y - 4, width + 8, height + 8, height / 2 , height / 2);
g.setColor(Color.DARK_GRAY);
g.drawString(name, x, y + height);
}
/**
* Rebuild display to reflect settings
*/
public void buildFromSettings() {
layers = settings.getLayers();
shape = (Shape) settings.getSetting(GraphicalSettings.GRAPHICAL_SHAPE);
requestPredictiveData();
}
/**
* Get the settings for this manifestation
* @return the settings for this manifestation
*/
public GraphicalSettings getSettings() {
return settings;
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return feedProviderList;
}
@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) {
AbstractComponent component = getManifestedComponent();
FeedProvider provider = getFeedProvider(component);
if (provider != null) {
List<Map<String, String>> feedData = data.get(provider.getSubscriptionId());
if (feedData != null && !feedData.isEmpty()) {
Map<String, String> feedDataItem = feedData.get(feedData.size() - 1);
List<RenderingInfo> riList = new ArrayList<RenderingInfo>();
riList.add(provider.getRenderingInfo(feedDataItem));
/* Get updates from the appropriate evaluator */
if (settings.getSetting(GraphicalSettings.GRAPHICAL_EVALUATOR) instanceof AbstractComponent) {
AbstractComponent comp = (AbstractComponent) settings.getSetting(GraphicalSettings.GRAPHICAL_EVALUATOR);
riList.add(comp.getCapability(Evaluator.class).evaluate(data, Collections.singletonList(provider)));
}
/* Send both numeric state and evaluator state to brushes */
if (riList.get(0).isPlottable()) { // ...only if we have new feed data
for (RenderingInfo ri : riList) {
for (Brush b : layers) {
if (b instanceof StateSensitive) {
((StateSensitive) b).setState(ri.getValueText());
}
}
}
}
// TODO: Show status character on LOS
}
}
repaint(); // Update the graphical representation
// TODO: Only repaint on change?
}
private void requestPredictiveData() {
/* Explicitly request data if we're using a predictive feed */
boolean predictive = false;
for (FeedProvider fp : feedProviderList) {
if (fp != null && fp.isPrediction()) {
predictive = true;
break;
}
}
if (predictive) {
requestData(feedProviderList, System.currentTimeMillis(), System.currentTimeMillis(),
new DataTransformation() {
@Override
public void transform(
Map<String, List<Map<String, String>>> data,
long startTime, long endTime) {}
},
this,
true);
}
/* We expect non-predictive feeds to push their data */
}
@Override
public void updateMonitoredGUI() {
this.buildFromSettings();
}
@Override
public void updateMonitoredGUI(PropertyChangeEvent evt) {
this.buildFromSettings();
// TODO: This may be where to catch naming context changes
}
@Override
public void render(Map<String, List<Map<String, String>>> data) {
updateFromFeed(data);
}
} | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_GraphicalManifestation.java |
901 | new DataTransformation() {
@Override
public void transform(
Map<String, List<Map<String, String>>> data,
long startTime, long endTime) {}
}, | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_GraphicalManifestation.java |
902 | public class GraphicalManifestationTest {
private static final int SIZE = 300;
private static final String SUBSCRIPTION_ID = "mock";
private static final Color BACKGROUND = Color.pink;
private GraphicalManifestation view;
Map<String, List<Map<String, String>>> feedData;
@Mock private AbstractComponent mockComponent;
@Mock private FeedProvider mockProvider;
@Mock private ViewInfo mockViewInfo;
@Mock private RenderingInfo mockRenderingInfo;
@Mock private ExtendedProperties mockViewProperties;
@SuppressWarnings("unchecked")
@BeforeTest
public void setupTest() {
MockitoAnnotations.initMocks(this);
Mockito.when(mockComponent.getCapability(FeedProvider.class)).thenReturn(mockProvider);
Mockito.when(mockProvider.getSubscriptionId()).thenReturn(SUBSCRIPTION_ID);
Mockito.when(mockProvider.getRenderingInfo(Mockito.anyMap())).thenReturn(mockRenderingInfo);
Mockito.when(mockRenderingInfo.isPlottable()).thenReturn(true);
Mockito.when(mockRenderingInfo.getValueText()).thenReturn("50");
view = new GraphicalManifestation(mockComponent, mockViewInfo) {
private static final long serialVersionUID = -3323166317731283322L;
public ExtendedProperties getViewProperties() {
return mockViewProperties;
}
};
feedData =
new HashMap<String, List<Map<String, String>>>();
Map<String, String> dummyMap = new HashMap<String,String>();
feedData.put(SUBSCRIPTION_ID, Collections.singletonList(dummyMap));
}
@Test
public void testManifestationPaint() {
Shape shape = (Shape) view.getSettings().getSetting(GraphicalSettings.GRAPHICAL_SHAPE);
List<Brush> brushList = view.getSettings().getLayers();
view.setSize(SIZE, SIZE);
view.setBackground(BACKGROUND);
final BufferedImage viewImage = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_RGB);
final BufferedImage manualImage = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_RGB);
view.updateFromFeed(feedData);
view.paint(viewImage.getGraphics());
Graphics g = manualImage.getGraphics();
g.setColor(BACKGROUND);
g.fillRect(0,0,300,300);
for (Brush brush : brushList) {
if (brush instanceof StateSensitive) {
((StateSensitive) brush).setInterval(0, 100);
((StateSensitive) brush).setState("50");
}
// Bounds shrunken by 5%
brush.draw(shape, g, new Rectangle(15,15,270,270));
}
for (int x = 0; x < 300; x++) {
for (int y = 0; y < 300; y++) {
Assert.assertEquals(viewImage.getRGB(x, y), manualImage.getRGB(x, y));
}
}
}
@Test
public void testControlManifestation() {
JComponent c = view.initializeControlManifestation();
Assert.assertTrue(findControlPanel(c));
}
private boolean findControlPanel(JComponent component) {
boolean result = component instanceof GraphicalControlPanel;
for (Component c : component.getComponents()) {
if (c instanceof JComponent) {
result |= findControlPanel((JComponent) c);
}
}
return result;
}
@Test
public void testResponseToSettingChange() {
Shape shape = (Shape) view.getSettings().getSetting(GraphicalSettings.GRAPHICAL_SHAPE);
List<Brush> originalList = view.getSettings().getLayers();
view.setSize(SIZE, SIZE);
view.setBackground(BACKGROUND);
final BufferedImage viewImage = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_RGB);
final BufferedImage manualImage = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_RGB);
Graphics g = manualImage.getGraphics();
g.setColor(BACKGROUND);
g.fillRect(0,0,300,300);
for (Brush brush : originalList) {
if (brush instanceof StateSensitive) {
((StateSensitive) brush).setInterval(0, 100);
((StateSensitive) brush).setState("50");
}
// Bounds shrunken by 5%
brush.draw(shape, g, new Rectangle(15,15,270,270));
}
/* Try a different outline color */
Mockito.when(mockViewProperties.getProperty(GraphicalSettings.GRAPHICAL_OUTLINE_COLOR, String.class))
.thenReturn("Color4");
Color color = (Color) view.getSettings().getNamedObject("Color4");
view.updateMonitoredGUI();
view.updateFromFeed(feedData);
view.paint(viewImage.getGraphics());
for (int x = 0; x < 300; x++) {
for (int y = 0; y < 300; y++) {
if (viewImage.getRGB(x, y) == color.getRGB()) {
/* Outline should be different */
Assert.assertFalse(viewImage.getRGB(x, y) == manualImage.getRGB(x, y));
} else {
/* Everyting else should still be the same */
Assert.assertTrue (viewImage.getRGB(x, y) == manualImage.getRGB(x, y));
}
}
}
}
@Test
public void testVisibleFeedProvider() {
Collection<FeedProvider> providers = view.getVisibleFeedProviders();
Assert.assertEquals(providers.size(), 1);
Assert.assertEquals(providers.iterator().next(), mockProvider);
}
} | false | dynamicGraphics_src_test_java_gov_nasa_arc_mct_graphics_view_GraphicalManifestationTest.java |
903 | view = new GraphicalManifestation(mockComponent, mockViewInfo) {
private static final long serialVersionUID = -3323166317731283322L;
public ExtendedProperties getViewProperties() {
return mockViewProperties;
}
}; | false | dynamicGraphics_src_test_java_gov_nasa_arc_mct_graphics_view_GraphicalManifestationTest.java |
904 | public class GraphicalSettings {
public static final String NO_EVALUATOR = "No Evaluator";
private GraphicalManifestation manifestation;
private static Map<String, Shape> shapeMap;
private static Map<String, Color> colorMap;
private static Map<String, String> defaultMap;
private static Map<String, FillProvider> fillMap;
private Map<Object, String> reverseMap;
private Map<String, Object> evaluatorMap;
private Map<Object, List<String>> enumerationMap; //Maps eval name to possible states
public GraphicalSettings (GraphicalManifestation manifestation) {
this.manifestation = manifestation;
initializeEvaluatorMap();
reverseMap = new HashMap<Object, String>();
addToReverseMap(shapeMap);
addToReverseMap(colorMap);
addToReverseMap(evaluatorMap);
}
/* Setting names for persistence */
//TODO shorten names
public static final String GRAPHICAL_SHAPE = "GraphicalShapeSetting";
public static final String GRAPHICAL_BACKGROUND_COLOR = "GraphicalBackgroundColor";
public static final String GRAPHICAL_OUTLINE_COLOR = "GraphicalOutlineColor";
public static final String GRAPHICAL_OUTLINE_WEIGHT = "GraphicalOutlineWeight";
public static final String GRAPHICAL_FOREGROUND_FILL = "GraphicalFillStyle";
public static final String GRAPHICAL_FOREGROUND_COLOR = "GraphicalFillColor";
public static final String GRAPHICAL_FOREGROUND_MIN = "GraphicalFillMinimum";
public static final String GRAPHICAL_FOREGROUND_MAX = "GraphicalFillMaximum";
public static final String GRAPHICAL_EVALUATOR = "GraphicalEvaluator";
public static final String GRAPHICAL_EVALUATOR_MAP = "GraphicalEvaluatorMap";
public static final String DEFAULT_SHAPE = "Ellipse";
public static final String DEFAULT_BACKGROUND_COLOR = "Color0";
public static final String DEFAULT_OUTLINE_COLOR = "Color1";
public static final String DEFAULT_OUTLINE_WEIGHT = "10";
public static final String DEFAULT_FOREGROUND_FILL = "East";
public static final String DEFAULT_FOREGROUND_COLOR = "Color2";
public static final String DEFAULT_FOREGROUND_MIN = "0";
public static final String DEFAULT_FOREGROUND_MAX = "100";
public static final String DEFAULT_EVALUATOR = NO_EVALUATOR;
public static final String DEFAULT_EVALUATOR_MAP = "";
/* Initialize maps */
static {
shapeMap = new LinkedHashMap<String, Shape>();
shapeMap.put("Ellipse", new Ellipse2D.Float(0, 0, 1, 1));
shapeMap.put("Rectangle", new Rectangle2D.Float(1, 1, 2, 2) );
shapeMap.put("RoundRectangle", new RoundRectangle2D.Float(1.0f, 1.0f, 1,1, 0.5f, 0.5f) );
for (int i = 3; i <= 6; i++) {
shapeMap.put("Polygon" + i, new RegularPolygon(i));
}
/* TODO - this needs to be color schemed */
/* Most colors taken from canvas ControlareaFormattingConstants */
colorMap = new LinkedHashMap<String, Color>();
colorMap.put("Color0", Color.DARK_GRAY.darker());
colorMap.put("Color1", Color.DARK_GRAY);
colorMap.put("Color2", Color.BLUE);
colorMap.put("Color3", Color.RED);
colorMap.put("Color4", Color.green);
colorMap.put("Color5", new Color(000, 128, 000));
colorMap.put("Color6", new Color(032, 179, 170));
colorMap.put("Color7", new Color(152, 251, 152));
colorMap.put("Color8", new Color(255, 140, 000));
colorMap.put("Color9", new Color(255, 000, 255));
colorMap.put("Color10", new Color(255, 69, 000));
colorMap.put("Color11", new Color(255, 215, 000));
colorMap.put("Color12", new Color(047, 79, 79));
colorMap.put("Color13", new Color(128, 128, 128));
colorMap.put("Color14", new Color(100, 149, 237));
colorMap.put("Color15", new Color(000, 49, 042));
colorMap.put("Color16", new Color(000, 176, 176));
colorMap.put("Color17", new Color(102, 051, 255));
fillMap = new LinkedHashMap<String, FillProvider>();
fillMap.put("Static", new FillProvider());
fillMap.put("North", new ClippedFillProvider(AxisClip.Y_AXIS, AxisClip.DECREASING));
fillMap.put("South", new ClippedFillProvider(AxisClip.Y_AXIS, AxisClip.INCREASING));
fillMap.put("East", new ClippedFillProvider(AxisClip.X_AXIS, AxisClip.INCREASING));
fillMap.put("West", new ClippedFillProvider(AxisClip.X_AXIS, AxisClip.DECREASING));
fillMap.put("Expanding", new ExpandingFillProvider());
defaultMap = new HashMap<String, String>();
defaultMap.put(GRAPHICAL_SHAPE, DEFAULT_SHAPE);
defaultMap.put(GRAPHICAL_BACKGROUND_COLOR, DEFAULT_BACKGROUND_COLOR);
defaultMap.put(GRAPHICAL_OUTLINE_COLOR, DEFAULT_OUTLINE_COLOR);
defaultMap.put(GRAPHICAL_OUTLINE_WEIGHT, DEFAULT_OUTLINE_WEIGHT);
defaultMap.put(GRAPHICAL_FOREGROUND_FILL, DEFAULT_FOREGROUND_FILL);
defaultMap.put(GRAPHICAL_FOREGROUND_COLOR, DEFAULT_FOREGROUND_COLOR);
defaultMap.put(GRAPHICAL_FOREGROUND_MIN, DEFAULT_FOREGROUND_MIN);
defaultMap.put(GRAPHICAL_FOREGROUND_MAX, DEFAULT_FOREGROUND_MAX);
defaultMap.put(GRAPHICAL_EVALUATOR, DEFAULT_EVALUATOR);
defaultMap.put(GRAPHICAL_EVALUATOR_MAP, DEFAULT_EVALUATOR_MAP);
}
private void initializeEvaluatorMap() {
evaluatorMap = new LinkedHashMap<String, Object>();
evaluatorMap.put(NO_EVALUATOR, NO_EVALUATOR);
enumerationMap = new HashMap<Object, List<String>>();
enumerationMap.put(NO_EVALUATOR, Collections.<String> emptyList());
AbstractComponent component = manifestation.getManifestedComponent();
addEvaluator(component);
for (AbstractComponent parent : component.getReferencingComponents()) {
addEvaluator(parent);
}
}
private void addEvaluator(AbstractComponent comp) {
Evaluator evaluator = comp.getCapability(Evaluator.class);
if (evaluator == null) return;
// Can only handle enum & imars/enum ...
String language = evaluator.getLanguage();
if (!(language.equals("enum") || language.equals("imars/enum"))) {
return;
}
// Track possible enumerations
List<String> enumerations = new ArrayList<String> ();
StringTokenizer codes = new StringTokenizer(evaluator.getCode(), "\t");
while (codes.hasMoreTokens()) {
String code = codes.nextToken();
int skip = 0;
if (language.equals("enum")) skip = 2; // Skip first two terms
if (language.equals("imars/enum")) skip = 1; // Skip first token only
while (skip-- > 0) {
if (code.contains(" "))
code = code.substring(code.indexOf(" ") + 1);
else
code = "";
}
if (code != "") {
enumerations.add(code);
}
}
evaluatorMap.put(comp.getDisplayName(), comp);
enumerationMap.put(comp, enumerations);
}
private void addToReverseMap(Map<String, ?> map) {
for (Entry<String, ?> e : map.entrySet()) {
reverseMap.put(e.getValue(), e.getKey());
}
}
/**
* Get a named object (for instance, a shape from the settings shape map, or
* color from the settings color map)
* @param name the name of the object
* @return the object so named
*/
public Object getNamedObject(String name) {
if (shapeMap.containsKey(name)) return shapeMap.get(name);
if (colorMap.containsKey(name)) return colorMap.get(name);
if (fillMap.containsKey(name)) return name; // Fill names are mapped only internally
return null;
}
/**
* Get the list of brushes which, when drawn, will reflect current settings.
* @return a list of brushes
*/
public List<Brush> getLayers() {
List<Brush> brushes = new ArrayList<Brush>();
brushes.add(new Fill((Color) getSetting(GRAPHICAL_BACKGROUND_COLOR)));
FillProvider provider = fillMap.get((String) getSetting(GRAPHICAL_FOREGROUND_FILL));
Object evaluator = getSetting(GRAPHICAL_EVALUATOR);
if (evaluator == NO_EVALUATOR) {
Brush b = provider.getFill((Color) getSetting(GRAPHICAL_FOREGROUND_COLOR));
Double minimum = Double.parseDouble((String) getSetting(GRAPHICAL_FOREGROUND_MIN));
Double maximum = Double.parseDouble((String) getSetting(GRAPHICAL_FOREGROUND_MAX));
if (b instanceof StateSensitive) ((StateSensitive) b).setInterval(minimum, maximum);
brushes.add(b);
} else {
// Build evaluator brushes
Object evMapSetting = getSetting(GRAPHICAL_EVALUATOR_MAP);
if (evMapSetting instanceof Map) {
Map evMap = (Map) evMapSetting;
for (Object entry : evMap.entrySet()) {
if (entry instanceof Map.Entry) {
Object key = ((Map.Entry) entry).getKey();
Object value = ((Map.Entry) entry).getValue();
if (value instanceof Color && key instanceof String) {
Fill b = provider.getFill((Color) value);
Double minimum = Double.parseDouble((String) getSetting(GRAPHICAL_FOREGROUND_MIN));
Double maximum = Double.parseDouble((String) getSetting(GRAPHICAL_FOREGROUND_MAX));
b.setInterval(minimum, maximum);
brushes.add(new ConditionalBrush(b, (String) key));
}
}
}
}
}
brushes.add(new Outline((Color) getSetting(GRAPHICAL_OUTLINE_COLOR)));
return brushes;
}
/**
* Apply the current settings to the managed view.
*/
public void updateManifestation() {
manifestation.buildFromSettings();
manifestation.getManifestedComponent().save();
}
/**
* Get all shapes that are supported by settings
* @return a collection of available shapes
*/
public Collection<Shape> getSupportedShapes() {
return shapeMap.values();
}
/**
* Get all colors which are supported by settings
* @return a collection of available colors
*/
public Collection<Color> getSupportedColors() {
return colorMap.values();
}
/**
* Get all evaluators which are supported by these settings
* @return a collection of evaluators available for the viewed component
*/
public Collection<Object> getSupportedEvaluators() {
return evaluatorMap.values();
}
/**
* Get the names of all fill types which are supported by these settings
* @return a set of names of available fills
*/
public Set<String> getSupportedFills() {
return fillMap.keySet();
}
/**
*
* @param component the component which provides the evaluator
* @return a collection of known possible evaluation outputs
*/
public Collection<String> getSupportedEnumerations() {
return enumerationMap.get(getSetting(GRAPHICAL_EVALUATOR));
}
/**
* Determine whether or not the specified key is the name of a setting
* @param key the name to check
* @return true if this is the name of a setting, false if not
*/
public boolean isValidKey(String key) {
return defaultMap.containsKey(key);
}
/**
* Gets the current setting associated with the specified key, in its
* String form. If it has not been set in a manifestation, the default will
* be applied and returned.
* @param key the name of the setting
* @return the current value, as a string
*/
private String get(String key) {
String value = manifestation.getViewProperties().getProperty(key, String.class);
if (value == null) {
if (!isValidKey(key)) return null;
set (key, defaultMap.get(key));
value = defaultMap.get(key);
}
return value;
}
/**
* Set the value for a specific setting. (In its string form - direct
* to the manifestation.)
* @param key the name of the setting
* @param value the new value
*/
private void set(String key, String value) {
ExtendedProperties viewProperties = manifestation.getViewProperties();
viewProperties.setProperty(key, value);
}
/**
* Get the object represented by current settings.
* @param name the name of the settings
* @return the object which represents the current choice
*/
public Object getSetting (String name) {
String choice = get(name);
if (shapeMap.containsKey(choice)) return shapeMap.get(choice);
if (colorMap.containsKey(choice)) return colorMap.get(choice);
if (fillMap.containsKey(choice)) return choice; //Not remapped
if (evaluatorMap.containsKey(choice)) return evaluatorMap.get(choice);
if (name.equals(GRAPHICAL_EVALUATOR_MAP)) return decodeMap(choice);
else return choice;
}
/**
* Set the value of a setting to correspond with the given Object. Note that
* this does nothing if the Object is not supported
* @param key the name of the setting
* @param value the object to make the current setting
*/
public void setByObject (String key, Object value) {
if (reverseMap.containsKey(value)) {
set(key, reverseMap.get(value));
} else if (value instanceof String) { // Fill just publishes keys
set(key, (String) value);
} else if (value instanceof Map) {
set(key, encodeMap((Map) value));
}
}
/**
* Turns a string, as stored in settings ("OK\tColor0\nFAIL\tColor1\n", for example)
* into a corresponding map.
* @param str the string form of the map, as made by encodeMap
* @return a Map object representing the string->color mappings
*/
private Map<String, Color> decodeMap (String str) {
Map<String, Color> map = new LinkedHashMap<String, Color>();
StringTokenizer mapTokens = new StringTokenizer(str, "\n");
while (mapTokens.hasMoreTokens()) {
String pair = mapTokens.nextToken();
if (!pair.isEmpty()) {
StringTokenizer entryTokens = new StringTokenizer(pair, "\t");
if (entryTokens.countTokens() == 2) {
String key = entryTokens.nextToken();
Color value = colorMap.get(entryTokens.nextToken());
map.put(key, value);
}
}
}
return map;
}
/**
* Turns a map of Strings to Colors into a string representation
* ("OK=>Color0;FAIL=>Color1;") for storage in settings
* @param map the evaluation->color mappings
* @return a string describing the same map
*/
private String encodeMap (Map map) {
StringBuilder s = new StringBuilder();
Set keySet = map.keySet();
for (Object plainKey : keySet) {
if (plainKey instanceof String) {
String key = (String) plainKey;
String value = reverseMap.get(map.get(key));
if (value != null) {
s.append(key);
s.append("\t");
s.append(value);
s.append("\n");
}
}
}
return s.toString();
}
private static class FillProvider {
public Fill getFill(Color color) {
return new Fill(color);
}
}
private static class ExpandingFillProvider extends FillProvider {
@Override
public Fill getFill(Color color) {
return new ScalingFill(color);
}
}
private static class ClippedFillProvider extends FillProvider {
private int axis;
private int direction;
public ClippedFillProvider(int axis, int direction) {
this.axis = axis;
this.direction = direction;
}
@Override
public Fill getFill(Color color) {
return new ClippedFill(color, axis, direction);
}
}
} | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_GraphicalSettings.java |
905 | private static class ClippedFillProvider extends FillProvider {
private int axis;
private int direction;
public ClippedFillProvider(int axis, int direction) {
this.axis = axis;
this.direction = direction;
}
@Override
public Fill getFill(Color color) {
return new ClippedFill(color, axis, direction);
}
} | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_GraphicalSettings.java |
906 | private static class ExpandingFillProvider extends FillProvider {
@Override
public Fill getFill(Color color) {
return new ScalingFill(color);
}
} | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_GraphicalSettings.java |
907 | private static class FillProvider {
public Fill getFill(Color color) {
return new Fill(color);
}
} | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_GraphicalSettings.java |
908 | public class GraphicalSettingsTest {
private static final String ENUMERATOR_NAME = "Enumerator";
private GraphicalManifestation mockView;
private AbstractComponent mockEnumerator;
@Mock private AbstractComponent mockComponent;
@Mock private ExtendedProperties mockViewProperties;
@Mock private Evaluator mockEvaluator;
private GraphicalSettings settings;
@BeforeMethod
public void setup() {
MockitoAnnotations.initMocks(this);
mockView = new GraphicalManifestation(mockComponent,
new ViewInfo(GraphicalManifestation.class,"", ViewType.OBJECT)) {
private static final long serialVersionUID = 6036948129496070106L;
public ExtendedProperties getViewProperties() {
return mockViewProperties;
}
};
Mockito.when(mockComponent.getCapability(Evaluator.class)).thenReturn(null);
Mockito.when(mockComponent.getReferencingComponents()).thenReturn(Collections.<AbstractComponent>emptyList());
Mockito.when(mockEvaluator.getDisplayName()).thenReturn("Phony evaluator");
Mockito.when(mockEvaluator.getLanguage()).thenReturn("enum");
Mockito.when(mockEvaluator.getCode()).thenReturn("= 0 abc\t> 0 xyz");
mockEnumerator = new AbstractComponent() {
@SuppressWarnings("unchecked")
@Override
protected <T> T handleGetCapability(Class<T> capability) {
if (capability.isAssignableFrom(mockEvaluator.getClass()))
return (T) mockEvaluator;
else
return null;
}
};
mockEnumerator.setDisplayName(ENUMERATOR_NAME);
settings = new GraphicalSettings(mockView);
}
@SuppressWarnings("unchecked") /* Unchecked is suppressing so we can mock view properties */
@Test
public void testDefaults() {
Mockito.when(mockViewProperties.getProperty(Mockito.anyString(), Mockito.any(Class.class))).thenReturn(null);
Assert.assertEquals(settings.getSetting(GraphicalSettings.GRAPHICAL_BACKGROUND_COLOR),
settings.getNamedObject(GraphicalSettings.DEFAULT_BACKGROUND_COLOR));
Assert.assertEquals(settings.getSetting(GraphicalSettings.GRAPHICAL_FOREGROUND_COLOR),
settings.getNamedObject(GraphicalSettings.DEFAULT_FOREGROUND_COLOR));
Assert.assertEquals(settings.getSetting(GraphicalSettings.GRAPHICAL_FOREGROUND_FILL),
settings.getNamedObject(GraphicalSettings.DEFAULT_FOREGROUND_FILL));
Assert.assertEquals(settings.getSetting(GraphicalSettings.GRAPHICAL_OUTLINE_COLOR),
settings.getNamedObject(GraphicalSettings.DEFAULT_OUTLINE_COLOR));
Assert.assertEquals(settings.getSetting(GraphicalSettings.GRAPHICAL_SHAPE),
settings.getNamedObject(GraphicalSettings.DEFAULT_SHAPE));
}
@SuppressWarnings("unchecked") /* Unchecked is suppressing so we can mock view properties */
@Test
public void testLayerProduction() {
List<Brush> layers;
/* Does it produce regular fills? */
Mockito.when(mockViewProperties.getProperty(Mockito.anyString(), Mockito.any(Class.class))).thenReturn(null);
layers = settings.getLayers();
Assert.assertEquals(layers.size(), 3); // Background, foreground, outline
Assert.assertTrue(layers.get(0) instanceof Fill);
Assert.assertTrue(layers.get(1) instanceof Fill);
Assert.assertTrue(layers.get(2) instanceof Outline);
/* Does it produce evaluator views? */
Mockito.when(mockViewProperties.getProperty(GraphicalSettings.GRAPHICAL_EVALUATOR_MAP, String.class))
.thenReturn("A\tColor1\nB\tColor2\n");
Mockito.when(mockViewProperties.getProperty(GraphicalSettings.GRAPHICAL_EVALUATOR, String.class))
.thenReturn("Mock Evaluator");
layers = settings.getLayers();
Assert.assertEquals(layers.size(), 4);
Assert.assertTrue(layers.get(0) instanceof Fill);
Assert.assertTrue(layers.get(1) instanceof ConditionalBrush);
Assert.assertTrue(layers.get(2) instanceof ConditionalBrush);
Assert.assertTrue(layers.get(3) instanceof Outline);
}
/* Should be able to parse the mock evaluator */
@Test
public void testEnumerations() {
Assert.assertTrue(settings.getSupportedEnumerations().isEmpty());
Mockito.when(mockComponent.getReferencingComponents()).thenReturn(Collections.<AbstractComponent>singletonList(mockEnumerator));
Mockito.when(mockViewProperties.getProperty(GraphicalSettings.GRAPHICAL_EVALUATOR, String.class))
.thenReturn(ENUMERATOR_NAME);
settings = new GraphicalSettings(mockView);
Collection<String> enumerations = settings.getSupportedEnumerations();
Assert.assertNotNull(enumerations);
Assert.assertEquals(enumerations.size(), 2);
Iterator<String> it = enumerations.iterator();
Assert.assertEquals(it.next(), "abc");
Assert.assertEquals(it.next(), "xyz");
}
} | false | dynamicGraphics_src_test_java_gov_nasa_arc_mct_graphics_view_GraphicalSettingsTest.java |
909 | new ViewInfo(GraphicalManifestation.class,"", ViewType.OBJECT)) {
private static final long serialVersionUID = 6036948129496070106L;
public ExtendedProperties getViewProperties() {
return mockViewProperties;
}
}; | false | dynamicGraphics_src_test_java_gov_nasa_arc_mct_graphics_view_GraphicalSettingsTest.java |
910 | mockEnumerator = new AbstractComponent() {
@SuppressWarnings("unchecked")
@Override
protected <T> T handleGetCapability(Class<T> capability) {
if (capability.isAssignableFrom(mockEvaluator.getClass()))
return (T) mockEvaluator;
else
return null;
}
}; | false | dynamicGraphics_src_test_java_gov_nasa_arc_mct_graphics_view_GraphicalSettingsTest.java |
911 | public class SVGRasterizer {
private Dimension nextRenderingSize = null;
private Dimension lastRenderingSize = null;
private SVGDocument svgDocument = null;
private BufferedImage latestImage = null;
private GraphicsNode graphicsNode = null;
private Runnable callback = null;
private boolean isLoading = true;
/**
* Create a new rasterizer to convert an SVG document
* to BufferedImages, for display on a specific component
* Note that loading/parsing and rendering are both done
* asynchronously.
* @param documentURL the URL of the document to rasterize
*/
public SVGRasterizer(String documentURL) {
UserAgent userAgent = new UserAgentAdapter();
SVGDocumentLoader loader = new SVGDocumentLoader(documentURL,
new DocumentLoader(userAgent));
loader.addSVGDocumentLoaderListener(new SVGRasterizerListener());
loader.start();
}
/**
* Inject behavior to be called when rendering is complete
* @param callback the behavior to run after rendering
*/
public void setCallback(Runnable callback) {
this.callback = callback;
}
/**
* Request a raster image of the loaded SVG document,
* at a specified width and height.
* Note that rendering will be done asynchronously;
* subsequent calls to getLatestImage() will return
* the rendered image once complete (and the previously
* rendered image until then)
* @param width the width in pixels at which to render
* @param height the height in pixels at which to render
*/
public void requestRender(int width, int height) {
width = (width < 1) ? 1 : width;
height = (height < 1) ? 1 : height;
if (latestImage != null &&
width == latestImage.getWidth() &&
height == latestImage.getHeight()) return;
nextRenderingSize = new Dimension (width, height);
renderIfReady();
}
/**
* Get the most recently rendered raster image of this
* SVG document. This may be null if no renders have
* completed, and may not match the size of the last
* rendering request if rendering is incomplete.
* @return
*/
public BufferedImage getLatestImage() {
return latestImage;
}
/**
* Check to see if document loading failed
* @return true if the document could not be loaded/parsed;
* false if it was successful, or is still loading
*/
public boolean hasFailed() {
return graphicsNode == null && !isLoading;
}
/**
* Check to see if the document has been loaded & parsed
* @return true if loaded; otherwise false
*/
public boolean isLoaded() {
return graphicsNode != null;
}
/**
* Check to see if any rendering operation has completed
* (not necessarily the most recently requested one)
* @return true if an image is available; false if not
*/
public boolean isRendered() {
return latestImage != null;
}
/**
* Check to see if all rendering options have completed
* @return true if an up-to-date image is available
*/
public boolean isCurrent() {
return latestImage != null &&
nextRenderingSize == null &&
lastRenderingSize == null;
}
/**
* Check to see if the document is in the process of loading
* & parsing.
* @return true if loading & parsing; otherwise false
*/
public boolean isLoading() {
return isLoading;
}
private synchronized void renderIfReady() {
if (graphicsNode == null) return;
if (nextRenderingSize == null) return;
if (lastRenderingSize != null) return; // Still waiting
Dimension size = nextRenderingSize;
Rectangle2D bounds = graphicsNode.getPrimitiveBounds();
lastRenderingSize = nextRenderingSize;
nextRenderingSize = null;
// start renderer...
double widthScale = size.getWidth() / bounds.getWidth();
double heightScale = size.getHeight() / bounds.getHeight();
AffineTransform renderTransform = new AffineTransform();
renderTransform.scale(widthScale, heightScale);
renderTransform.translate(-bounds.getMinX(), -bounds.getMinY());
ImageRenderer renderer = new ConcreteImageRendererFactory().createStaticImageRenderer();
renderer.setTree(graphicsNode);
GVTTreeRenderer gvtRenderer = new GVTTreeRenderer(
renderer,
renderTransform,
true,
bounds,
size.width, size.height);
gvtRenderer.addGVTTreeRendererListener(new SVGRasterizerListener());
gvtRenderer.start();
}
private class SVGRasterizerListener implements SVGDocumentLoaderListener,
GVTTreeBuilderListener,
GVTTreeRendererListener {
/* SVGDocumentLoaderListener */
@Override
public void documentLoadingCancelled(SVGDocumentLoaderEvent arg0) {
isLoading = false;
if (callback != null) callback.run();
}
@Override
public void documentLoadingCompleted(SVGDocumentLoaderEvent arg0) {
svgDocument = arg0.getSVGDocument();
GVTTreeBuilder gvtBuilder;
gvtBuilder = new GVTTreeBuilder(svgDocument, new BridgeContext(new UserAgentAdapter()));
gvtBuilder.addGVTTreeBuilderListener(this);
gvtBuilder.start();
}
@Override
public void documentLoadingFailed(SVGDocumentLoaderEvent arg0) {
isLoading = false;
if (callback != null) callback.run();
}
@Override
public void documentLoadingStarted(SVGDocumentLoaderEvent arg0) {
}
/* GVTTreeBuilderListener */
@Override
public void gvtBuildCancelled(GVTTreeBuilderEvent arg0) {
isLoading = false;
if (callback != null) callback.run();
}
@Override
public void gvtBuildCompleted(GVTTreeBuilderEvent arg0) {
graphicsNode = arg0.getGVTRoot();
renderIfReady();
isLoading = false;
}
@Override
public void gvtBuildFailed(GVTTreeBuilderEvent arg0) {
isLoading = false;
if (callback != null) callback.run();
}
@Override
public void gvtBuildStarted(GVTTreeBuilderEvent arg0) {
}
/* GVTTreeRendererListener */
@Override
public void gvtRenderingCancelled(GVTTreeRendererEvent arg0) {
}
@Override
public synchronized void gvtRenderingCompleted(GVTTreeRendererEvent arg0) {
BufferedImage img = new BufferedImage(lastRenderingSize.width,
lastRenderingSize.height, BufferedImage.TYPE_INT_ARGB);
img.getGraphics().drawImage(arg0.getImage(),
0, 0, lastRenderingSize.width, lastRenderingSize.height,
0, 0, lastRenderingSize.width, lastRenderingSize.height,
null);
latestImage = img;
lastRenderingSize = null;
if (callback != null) callback.run();
}
@Override
public void gvtRenderingFailed(GVTTreeRendererEvent arg0) {
if (callback != null) callback.run();
}
@Override
public void gvtRenderingPrepare(GVTTreeRendererEvent arg0) {
}
@Override
public void gvtRenderingStarted(GVTTreeRendererEvent arg0) {
}
}
} | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_SVGRasterizer.java |
912 | private class SVGRasterizerListener implements SVGDocumentLoaderListener,
GVTTreeBuilderListener,
GVTTreeRendererListener {
/* SVGDocumentLoaderListener */
@Override
public void documentLoadingCancelled(SVGDocumentLoaderEvent arg0) {
isLoading = false;
if (callback != null) callback.run();
}
@Override
public void documentLoadingCompleted(SVGDocumentLoaderEvent arg0) {
svgDocument = arg0.getSVGDocument();
GVTTreeBuilder gvtBuilder;
gvtBuilder = new GVTTreeBuilder(svgDocument, new BridgeContext(new UserAgentAdapter()));
gvtBuilder.addGVTTreeBuilderListener(this);
gvtBuilder.start();
}
@Override
public void documentLoadingFailed(SVGDocumentLoaderEvent arg0) {
isLoading = false;
if (callback != null) callback.run();
}
@Override
public void documentLoadingStarted(SVGDocumentLoaderEvent arg0) {
}
/* GVTTreeBuilderListener */
@Override
public void gvtBuildCancelled(GVTTreeBuilderEvent arg0) {
isLoading = false;
if (callback != null) callback.run();
}
@Override
public void gvtBuildCompleted(GVTTreeBuilderEvent arg0) {
graphicsNode = arg0.getGVTRoot();
renderIfReady();
isLoading = false;
}
@Override
public void gvtBuildFailed(GVTTreeBuilderEvent arg0) {
isLoading = false;
if (callback != null) callback.run();
}
@Override
public void gvtBuildStarted(GVTTreeBuilderEvent arg0) {
}
/* GVTTreeRendererListener */
@Override
public void gvtRenderingCancelled(GVTTreeRendererEvent arg0) {
}
@Override
public synchronized void gvtRenderingCompleted(GVTTreeRendererEvent arg0) {
BufferedImage img = new BufferedImage(lastRenderingSize.width,
lastRenderingSize.height, BufferedImage.TYPE_INT_ARGB);
img.getGraphics().drawImage(arg0.getImage(),
0, 0, lastRenderingSize.width, lastRenderingSize.height,
0, 0, lastRenderingSize.width, lastRenderingSize.height,
null);
latestImage = img;
lastRenderingSize = null;
if (callback != null) callback.run();
}
@Override
public void gvtRenderingFailed(GVTTreeRendererEvent arg0) {
if (callback != null) callback.run();
}
@Override
public void gvtRenderingPrepare(GVTTreeRendererEvent arg0) {
}
@Override
public void gvtRenderingStarted(GVTTreeRendererEvent arg0) {
}
} | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_SVGRasterizer.java |
913 | public class SVGRasterizerTest {
private static final String CHECKER = new File("src/test/resources/checker.svg").toURI().toString();
private static final String BAD_FILE = "src/test/resources/NONEXISTANT.svg";
private static final int MAXIMUM_WAIT = 5000;
@Test
public void testDocumentFailure() throws Exception {
SVGRasterizer rasterizer = new SVGRasterizer(BAD_FILE);
Assert.assertNull(rasterizer.getLatestImage());
waitForLoad(rasterizer);
Assert.assertTrue(rasterizer.hasFailed());
}
@Test
public void testDocumentLoading() throws Exception {
SVGRasterizer rasterizer = new SVGRasterizer(CHECKER);
Assert.assertNull(rasterizer.getLatestImage());
waitForLoad(rasterizer);
Assert.assertTrue(rasterizer.isLoaded());
}
@Test
public void testDocumentRendering() throws Exception {
SVGRasterizer rasterizer = new SVGRasterizer(CHECKER);
Assert.assertNull(rasterizer.getLatestImage());
rasterizer.requestRender(100, 100 );
waitForCurrent(rasterizer);
Assert.assertEquals(rasterizer.getLatestImage().getWidth(), 100);
Assert.assertEquals(rasterizer.getLatestImage().getHeight(), 100);
checkForCheckers(rasterizer.getLatestImage());
BufferedImage stale;
synchronized (rasterizer) {
rasterizer.requestRender(1000, 1000);
Assert.assertFalse(rasterizer.isCurrent()); // Not current...
Assert.assertTrue(rasterizer.isRendered()); // ...but has something.
stale = rasterizer.getLatestImage();
Assert.assertTrue(stale.getWidth() == 100);
}
checkForCheckers(stale);
waitForCurrent(rasterizer);
Assert.assertEquals(rasterizer.getLatestImage().getWidth(), 1000);
Assert.assertEquals(rasterizer.getLatestImage().getHeight(), 1000);
checkForCheckers(rasterizer.getLatestImage());
/* Using the same value shouldn't require a new render */
rasterizer.requestRender(1000, 1000);
Assert.assertTrue(rasterizer.isCurrent());
}
private boolean calledBack;
@Test
public void testCallback() throws Exception {
calledBack = false;
SVGRasterizer rasterizer = new SVGRasterizer(CHECKER);
rasterizer.setCallback(new Runnable() {
public void run() { calledBack = true; }
});
// Instantiation doesn't call back
Assert.assertFalse(calledBack);
// Loading doesn't call back
waitForLoad(rasterizer);
Assert.assertFalse(calledBack);
// Rendering does call back
rasterizer.requestRender(10, 10);
waitForCurrent(rasterizer);
Assert.assertTrue(calledBack);
}
private void checkForCheckers(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
// Start at 2 to give a couple of pixels of leeway
for (int x = 2; x < w / 2 - 2; x++) {
for (int y = 2; y < h / 2 - 2; y++) {
/* Test for checkerboard pattern, or similar */
// Get colors from four quadrants
int[][] rgb = new int[2][2];
rgb[0][0] = img.getRGB( x, y);
rgb[0][1] = img.getRGB( x, h-y);
rgb[1][0] = img.getRGB(w-x, y);
rgb[1][1] = img.getRGB(w-x, h-y);
//Not reflected across x
Assert.assertFalse(rgb[0][0] == rgb[1][0]);
Assert.assertFalse(rgb[0][1] == rgb[1][1]);
//Not reflected across y
Assert.assertFalse(rgb[0][0] == rgb[0][1]);
Assert.assertFalse(rgb[1][0] == rgb[1][1]);
//But reflected diagonally
Assert.assertTrue (rgb[0][0] == rgb[1][1]);
Assert.assertTrue (rgb[1][0] == rgb[0][1]);
}
}
}
private void waitForLoad(SVGRasterizer rasterizer) throws Exception {
int i = 0;
while (rasterizer.isLoading() && i < MAXIMUM_WAIT) {
Thread.sleep(100);
i += 100;
}
Assert.assertTrue(i < MAXIMUM_WAIT); // Otherwise we timed out!
}
private void waitForCurrent(SVGRasterizer rasterizer) throws Exception {
int i = 0;
while (!rasterizer.isCurrent() && i < MAXIMUM_WAIT) {
Thread.sleep(100);
i += 100;
}
Assert.assertTrue(i < MAXIMUM_WAIT); // Otherwise we timed out!
}
} | false | dynamicGraphics_src_test_java_gov_nasa_arc_mct_graphics_view_SVGRasterizerTest.java |
914 | rasterizer.setCallback(new Runnable() {
public void run() { calledBack = true; }
}); | false | dynamicGraphics_src_test_java_gov_nasa_arc_mct_graphics_view_SVGRasterizerTest.java |
915 | public class StaticGraphicalView extends View {
private static ResourceBundle bundle = ResourceBundle.getBundle("GraphicsResourceBundle");
private static final long serialVersionUID = -6823838565608622054L;
private SVGRasterizer rasterizer = null;
private ImagePanel imagePanel = new ImagePanel();
public static final String VIEW_ROLE_NAME = bundle.getString("View_Name");
public StaticGraphicalView(AbstractComponent component, ViewInfo vi) {
super(component, vi);
setBackground(UIManager.getColor("background"));
setForeground(UIManager.getColor("foreground"));
imagePanel.setBackground(getBackground());
add(imagePanel);
if (component instanceof GraphicalComponent) {
GraphicalModel model = ((GraphicalComponent)component).getModelRole();
prepareGraphicalView(model.getGraphicURI());
} else {
prepareFailureLabel(bundle.getString("Component_Error"));
}
}
private void prepareGraphicalView(final String graphicURI) {
if (graphicURI.endsWith(".svg")) {
rasterizer = new SVGRasterizer(graphicURI);
rasterizer.setCallback(new Runnable() {
public void run() {
if (rasterizer.hasFailed()) {
prepareRasterImage(graphicURI); // Maybe the extension is wrong
} else {
imagePanel.setImage(rasterizer.getLatestImage());
}
repaint();
}
});
addComponentListener( new ComponentListener() {
@Override
public void componentHidden(ComponentEvent arg0) {
/* Get a smaller image - less memory use */
rasterizer.requestRender(50, 50);
}
@Override
public void componentMoved(ComponentEvent arg0) {
}
@Override
public void componentResized(ComponentEvent arg0) {
rasterizer.requestRender(getWidth(), getHeight());
}
@Override
public void componentShown(ComponentEvent arg0) {
rasterizer.requestRender(getWidth(), getHeight());
}
});
} else {
prepareRasterImage(graphicURI);
}
}
private void prepareRasterImage(String graphicURI) {
try {
BufferedImage img = ImageIO.read(new URL(graphicURI));
if (img != null) {
imagePanel.setImage(img);
} else {
prepareFailureLabel("Type_Error", graphicURI);
}
} catch (IOException ioe) {
prepareFailureLabel(
(ioe.getCause() instanceof FileNotFoundException) ?
"FileNotFound_Error" : "Location_Error",
graphicURI);
}
}
private void prepareFailureLabel(String bundleKey, String graphicURI) {
String failureString = bundle.getString(bundleKey);
prepareFailureLabel( String.format(failureString, graphicURI) );
}
private void prepareFailureLabel(final String failureText) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
removeAll();
setLayout(new BorderLayout());
JLabel failureLabel = new JLabel(failureText);
failureLabel.setBackground(getBackground());
failureLabel.setForeground(getForeground());
add(failureLabel, BorderLayout.NORTH);
repaint();
}
});
}
private class ImagePanel extends JPanel {
private static final long serialVersionUID = -2223786881389122841L;
private BufferedImage image = null;
public void setImage(BufferedImage image) {
this.image = image;
}
public void paint(Graphics g) {
super.paint(g);
if (image != null) {
g.drawImage(image, 0, 0, getWidth(), getHeight(),
0, 0, image.getWidth(), image.getHeight(), this);
}
}
}
} | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_StaticGraphicalView.java |
916 | rasterizer.setCallback(new Runnable() {
public void run() {
if (rasterizer.hasFailed()) {
prepareRasterImage(graphicURI); // Maybe the extension is wrong
} else {
imagePanel.setImage(rasterizer.getLatestImage());
}
repaint();
}
}); | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_StaticGraphicalView.java |
917 | addComponentListener( new ComponentListener() {
@Override
public void componentHidden(ComponentEvent arg0) {
/* Get a smaller image - less memory use */
rasterizer.requestRender(50, 50);
}
@Override
public void componentMoved(ComponentEvent arg0) {
}
@Override
public void componentResized(ComponentEvent arg0) {
rasterizer.requestRender(getWidth(), getHeight());
}
@Override
public void componentShown(ComponentEvent arg0) {
rasterizer.requestRender(getWidth(), getHeight());
}
}); | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_StaticGraphicalView.java |
918 | SwingUtilities.invokeLater(new Runnable() {
public void run() {
removeAll();
setLayout(new BorderLayout());
JLabel failureLabel = new JLabel(failureText);
failureLabel.setBackground(getBackground());
failureLabel.setForeground(getForeground());
add(failureLabel, BorderLayout.NORTH);
repaint();
}
}); | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_StaticGraphicalView.java |
919 | private class ImagePanel extends JPanel {
private static final long serialVersionUID = -2223786881389122841L;
private BufferedImage image = null;
public void setImage(BufferedImage image) {
this.image = image;
}
public void paint(Graphics g) {
super.paint(g);
if (image != null) {
g.drawImage(image, 0, 0, getWidth(), getHeight(),
0, 0, image.getWidth(), image.getHeight(), this);
}
}
} | false | dynamicGraphics_src_main_java_gov_nasa_arc_mct_graphics_view_StaticGraphicalView.java |
920 | public class StaticGraphicalViewTest {
private static final String CHECKER_SVG = new File("src/test/resources/checker.svg").toURI().toString();
private static final String CHECKER_PNG = new File("src/test/resources/checker.png").toURI().toString();
private static final String BAD_FILE = "src/test/resources/DOES_NOT_EXIST.svg";
private static final int PAINT_SIZE = 200;
@Mock private GraphicalComponent mockComponent;
private GraphicalModel checkersModelSVG = new GraphicalModel();
private GraphicalModel checkersModelPNG = new GraphicalModel();
private GraphicalModel badModel = new GraphicalModel();
@BeforeTest
public void setup() {
checkersModelSVG.setGraphicURI(CHECKER_SVG);
checkersModelPNG.setGraphicURI(CHECKER_PNG);
badModel.setGraphicURI(BAD_FILE);
MockitoAnnotations.initMocks(this);
}
@Test
public void testViewConstruction() throws Exception {
Mockito.when(mockComponent.getModelRole()).thenReturn(checkersModelPNG);
/* Create a new static graphical view */
StaticGraphicalView view = new StaticGraphicalView(mockComponent,
new ViewInfo(StaticGraphicalView.class, "", ViewType.OBJECT));;
/* Give image time to load or fail */
Thread.sleep(1000);
/* Should have one component (a JPanel) */
Assert.assertEquals(view.getComponentCount(), 1);
Assert.assertTrue(JPanel.class.isAssignableFrom(view.getComponent(0).getClass()));
}
@Test
public void testViewPaintingSVG() throws Exception {
Mockito.when(mockComponent.getModelRole()).thenReturn(checkersModelSVG);
/* Create a new static graphical view for the sample SVG */
StaticGraphicalView view = new StaticGraphicalView(mockComponent,
new ViewInfo(StaticGraphicalView.class, "", ViewType.OBJECT));;
/* Should force rendering */
view.setSize(PAINT_SIZE, PAINT_SIZE);
view.setVisible(true);
view.doLayout();
for (ComponentListener l : view.getComponentListeners()) {
l.componentResized(null);
}
Thread.sleep(1000);
/* We should be able to draw the checker pattern now */
BufferedImage testImage = new BufferedImage(PAINT_SIZE, PAINT_SIZE, BufferedImage.TYPE_INT_RGB);
view.paint(testImage.getGraphics());
checkForCheckers(testImage);
}
@Test
public void testViewPaintingPNG() throws Exception {
Mockito.when(mockComponent.getModelRole()).thenReturn(checkersModelPNG);
/* Create a new static graphical view for the sample PNG */
StaticGraphicalView view = new StaticGraphicalView(mockComponent,
new ViewInfo(StaticGraphicalView.class, "", ViewType.OBJECT));;
/* Should force rendering */
view.setSize(PAINT_SIZE, PAINT_SIZE);
view.setVisible(true);
view.doLayout();
for (ComponentListener l : view.getComponentListeners()) {
l.componentResized(null);
}
Thread.sleep(1000);
/* We should be able to draw the checker pattern now */
BufferedImage testImage = new BufferedImage(PAINT_SIZE, PAINT_SIZE, BufferedImage.TYPE_INT_RGB);
view.paint(testImage.getGraphics());
checkForCheckers(testImage);
}
private void checkForCheckers(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
// Start at 2 to give a couple of pixels of leeway
for (int x = 2; x < w / 2 - 2; x++) {
for (int y = 2; y < h / 2 - 2; y++) {
/* Test for checkerboard pattern, or similar */
// Get colors from four quadrants
int[][] rgb = new int[2][2];
rgb[0][0] = img.getRGB( x, y);
rgb[0][1] = img.getRGB( x, h-y);
rgb[1][0] = img.getRGB(w-x, y);
rgb[1][1] = img.getRGB(w-x, h-y);
//Not reflected across x
Assert.assertFalse(rgb[0][0] == rgb[1][0]);
Assert.assertFalse(rgb[0][1] == rgb[1][1]);
//Not reflected across y
Assert.assertFalse(rgb[0][0] == rgb[0][1]);
Assert.assertFalse(rgb[1][0] == rgb[1][1]);
//But reflected diagonally
Assert.assertTrue (rgb[0][0] == rgb[1][1]);
Assert.assertTrue (rgb[1][0] == rgb[0][1]);
}
}
}
} | false | dynamicGraphics_src_test_java_gov_nasa_arc_mct_graphics_view_StaticGraphicalViewTest.java |
921 | public class AbstractMCTViewManifestationInfoTest {
@Test
public void testContainsBorder() {
MCTViewManifestationInfo info = new MCTViewManifestationInfoImpl("TestName");
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_TOP));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_RIGHT));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_BOTTOM));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_LEFT));
List<Integer> borders = new ArrayList<Integer>();
borders.add(MCTViewManifestationInfo.BORDER_TOP);
info.setBorders(borders);
assertTrue(info.containsBorder(MCTViewManifestationInfo.BORDER_TOP));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_RIGHT));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_BOTTOM));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_LEFT));
}
@Test
public void testRemoveBorder() {
MCTViewManifestationInfo info = new MCTViewManifestationInfoImpl("TestPropertyString");
// Remove a border when no borders exist.
info.removeBorder(MCTViewManifestationInfo.BORDER_TOP);
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_TOP));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_RIGHT));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_BOTTOM));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_LEFT));
List<Integer> borders = new ArrayList<Integer>();
borders.add(MCTViewManifestationInfo.BORDER_TOP);
info.setBorders(borders);
// Remove a border that doesn't exist.
info.removeBorder(MCTViewManifestationInfo.BORDER_BOTTOM);
assertTrue(info.containsBorder(MCTViewManifestationInfo.BORDER_TOP));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_RIGHT));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_BOTTOM));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_LEFT));
// Remove a border that exists.
info.removeBorder(MCTViewManifestationInfo.BORDER_TOP);
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_TOP));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_RIGHT));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_BOTTOM));
assertFalse(info.containsBorder(MCTViewManifestationInfo.BORDER_LEFT));
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_AbstractMCTViewManifestationInfoTest.java |
922 | public abstract class AbstractViewListener implements ViewListener {
@Override
public void actionPerformed(TreeExpansionEvent event) {
// TODO Auto-generated method stub
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_AbstractViewListener.java |
923 | public interface ActionContext {
/**
* This method returns a collection of selected {@link View} instances.
* @return non-null collection of MCTViewManifestations
*/
public Collection<View> getSelectedManifestations();
/**
* This method returns the containing window's {@link View} instance.
* @return the window manifestation
*/
public View getWindowManifestation();
/**
* This method returns a collection of root level {@link View} instances.
* @return a collection of {@link View}
*/
public Collection<View> getRootManifestations();
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_ActionContext.java |
924 | public class ActionContextImpl implements ActionContext {
private AbstractComponent targetComponent;
private Set<JComponent> targetViewComponents = new LinkedHashSet<JComponent>();
private MCTHousing targetHousing;
private Collection<View> selectedManifestations = new LinkedHashSet<View>();
private AbstractComponent inspectorComponent;
/**
* Gets the target component for an action.
*
* @return the target component
*/
public AbstractComponent getTargetComponent() {
if (targetComponent == null) {
if (selectedManifestations.isEmpty())
return targetHousing != null ? targetHousing.getWindowComponent() : null;
else
return selectedManifestations.iterator().next().getManifestedComponent();
}
return targetComponent;
}
/**
* Sets the target component for an action.
*
* @param targetComponent the new target component
*/
public void setTargetComponent(AbstractComponent targetComponent) {
this.targetComponent = targetComponent;
}
/**
* Gets the target view manifestation, a Swing component
* that will be affected by the action. If there is more
* than one target view manifestation, return the first.
*
* @return the target view manifestation
*/
public JComponent getTargetViewComponent() {
if (targetViewComponents.isEmpty()) { return null; }
return targetViewComponents.iterator().next();
}
/**
* Gets the set of all target view manifestations.
*
* @return the target view manifestations
*/
public Set<JComponent> getAllTargetViewComponent() {
return targetViewComponents;
}
/**
* Adds another target view manifestation for an action.
*
* @param targetViewComponent the new target view manifestation
*/
public void addTargetViewComponent(JComponent targetViewComponent) {
this.targetViewComponents.add(targetViewComponent);
if (targetViewComponent instanceof View)
selectedManifestations.add((View) targetViewComponent);
}
/**
* Gets the housing containing the target component for an action.
*
* @return the target housing
*/
public MCTHousing getTargetHousing() {
return targetHousing;
}
/**
* Sets the target housing for an action.
*
* @param targetHousing the new target housing
*/
public void setTargetHousing(MCTHousing targetHousing) {
this.targetHousing = targetHousing;
}
@Override
public Collection<View> getSelectedManifestations() {
return Collections.unmodifiableCollection(selectedManifestations);
}
/** An empty action context used as a sentinel value. */
public static final ActionContextImpl NULL_CONTEXT = new ActionContextImpl();
@Override
public View getWindowManifestation() {
return targetHousing.getHousedViewManifestation();
}
@Override
public Collection<View> getRootManifestations() {
View housingManifestation = getWindowManifestation();
if (housingManifestation == null) { return Collections.emptyList(); }
Collection<View> viewManifestations = new ArrayList<View>();
CompositeViewManifestationProvider compositeProvider = (CompositeViewManifestationProvider)SwingUtilities.getAncestorOfClass(CompositeViewManifestationProvider.class, housingManifestation);
Collection<ViewProvider> manifestationsProviders = compositeProvider.getHousedManifestationProviders();
for (ViewProvider manifestProvider: manifestationsProviders) {
viewManifestations.add(manifestProvider.getHousedViewManifestation());
}
return viewManifestations;
}
/**
* Gets the inspector component this is set.
* @return instance of the inspector or null if the inspector is not active
*/
public AbstractComponent getInspectorComponent() {
return inspectorComponent;
}
/**
* Sets the inspector component if the action is triggered from the inspector.
* @param inspectorComponent to set as the inspector component
*/
public void setInspectorComponent(AbstractComponent inspectorComponent) {
this.inspectorComponent = inspectorComponent;
}
} | false | platform_src_main_java_gov_nasa_arc_mct_gui_ActionContextImpl.java |
925 | public final class ActionManager {
private static final Logger MENU_TOOLTIP_LOGGER = LoggerFactory.getLogger("gov.nasa.arc.mct.gui.menus");
private static Map<String, List<Class<? extends ContextAwareMenu>>> commandMenuMap = new HashMap<String, List<Class<? extends ContextAwareMenu>>>();
private static Map<String, List<Class<? extends ContextAwareAction>>> commandKeyActionMap = new HashMap<String, List<Class<? extends ContextAwareAction>>>();
/**
* Registers a new menu within MCT. Each menu within MCT
* has an identifier, its command key. This command key
* is used to look up the menu by ID using {@link #getMenu(String, ActionContextImpl)}.
*
* @param menuClass the class that implements the menu
* @param commandKey the unique identifier for the new menu
*/
public static void registerMenu(Class<? extends ContextAwareMenu> menuClass, String commandKey) {
List<Class<? extends ContextAwareMenu>> menuList = commandMenuMap.get(commandKey);
if (menuList == null) {
menuList = new ArrayList<Class<? extends ContextAwareMenu>>();
commandMenuMap.put(commandKey, menuList);
}
menuList.add(menuClass);
}
/**
* Finds a menu that has the given command key and is applicable
* in the given action context. If more than one such menu exits,
* return the first one registered.
*
* @param commandKey the command key of menus to find
* @param context the action context in which the menu should be applicable
* @return the applicable menu
*/
public static ContextAwareMenu getMenu(String commandKey, ActionContextImpl context) {
List<Class<? extends ContextAwareMenu>> menuList = commandMenuMap.get(commandKey);
if (menuList != null) {
for (Class<? extends ContextAwareMenu> menuClass : menuList) {
try {
ContextAwareMenu menu = menuClass.newInstance();
if (menu.canHandle(context)) {
menu.addMenuListener(MenuFactory.createMenuListener(menu));
// Populate built-in menus and/or menu items
menu.initialize();
// Populate extended menus and/or menu items
MenuExtensionManager manager = MenuExtensionManager.getInstance();
for (String menubarPath : menu.getExtensionMenubarPaths()) {
List<MenuItemInfo> extendedMenus = manager.getExtendedMenus(menubarPath);
menu.addMenuItemInfos(menubarPath, extendedMenus);
}
if (MENU_TOOLTIP_LOGGER.isDebugEnabled())
menu.setToolTipText(menu.getClass().getName());
return menu;
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* Registers an action for use within MCT. An action is associated
* with a command key, which ties a menu entry to an action.
*
* @param actionClass the class implementing the action
* @param commandKey the command key for the action
*/
public static void registerAction(Class<? extends ContextAwareAction> actionClass, String commandKey) {
List<Class<? extends ContextAwareAction>> actionClasses = commandKeyActionMap.get(commandKey);
if (actionClasses == null)
actionClasses = new ArrayList<Class<? extends ContextAwareAction>>();
actionClasses.add(actionClass);
commandKeyActionMap.put(commandKey, actionClasses);
}
/**
* Removes an action with the given class and command key.
*
* @param actionClass the class implementing the action
* @param commandKey the command key for the action to remove
*/
public static void unregisterAction(Class<? extends ContextAwareAction> actionClass, String commandKey) {
List<Class<? extends ContextAwareAction>> list = commandKeyActionMap.get(commandKey);
list.remove(actionClass);
if (list.isEmpty()) commandKeyActionMap.remove(commandKey);
}
/**
* Removes a submenu with the given class and command key.
*
* @param menuClass the class implementing the submenu
* @param commandKey the command key for the submenu to remove
*/
public static void unregisterMenu(Class<? extends ContextAwareMenu> menuClass, String commandKey) {
List<Class<? extends ContextAwareMenu>> list = commandMenuMap.get(commandKey);
list.remove(menuClass);
if (list.isEmpty()) commandKeyActionMap.remove(commandKey);
}
/**
* Removes a single action object.
*
* @param action the action to remove
*/
public static void deregisterAction(ContextAwareAction action) {
if (action.getValue(Action.ACTION_COMMAND_KEY) != null) {
if (commandKeyActionMap.containsKey(action.getValue(Action.ACTION_COMMAND_KEY))) {
if (commandKeyActionMap.get(action.getValue(Action.ACTION_COMMAND_KEY)) != null) {
commandKeyActionMap.remove(action.getValue(Action.ACTION_COMMAND_KEY));
}
}
}
}
/**
* Returns the first action that can handle the context.
* @param key commandKey
* @param context action context
* @return an action or null if none applicable
*/
public static ContextAwareAction getAction(String key, ActionContextImpl context) {
List<Class<? extends ContextAwareAction>> actionClassList = commandKeyActionMap.get(key);
if (actionClassList == null)
return null;
for (Class<? extends ContextAwareAction> actionClass : actionClassList) {
try {
ContextAwareAction action = actionClass.newInstance();
if (action.canHandle(context))
return action;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
} | false | platform_src_main_java_gov_nasa_arc_mct_gui_ActionManager.java |
926 | public class ActionManagerTest {
@Mock
private ActionContextImpl contextImpl;
@BeforeMethod
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testMenus() {
final String commandKey = "key";
ActionManager.registerMenu(TestContextAwareMenu.class, commandKey);
Assert.assertNotNull(ActionManager.getMenu(commandKey, contextImpl));
Assert.assertNull(ActionManager.getMenu("noKey", contextImpl));
}
@Test
public void testActions() {
final String actionKey = "key";
ActionManager.registerAction(TestContextAwareAction.class,actionKey);
Assert.assertNotNull(ActionManager.getAction(actionKey, contextImpl));
Assert.assertNull(ActionManager.getAction("junk", contextImpl));
ActionManager.unregisterAction(TestContextAwareAction.class, actionKey);
Assert.assertNull(ActionManager.getAction(actionKey, contextImpl));
// add the action and deregister it
ContextAwareAction action = null;
ActionManager.registerAction(TestContextAwareAction.class,actionKey);
Assert.assertNotNull(action = ActionManager.getAction(actionKey, contextImpl));
ActionManager.deregisterAction(action);
}
public static class TestContextAwareAction extends ContextAwareAction {
protected TestContextAwareAction() {
super("abc");
putValue(Action.ACTION_COMMAND_KEY, "key");
}
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
}
@Override
public boolean canHandle(ActionContext context) {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
public static class TestContextAwareMenu extends ContextAwareMenu {
private static final long serialVersionUID = 1L;
public boolean populated = false;
public TestContextAwareMenu() {
super("test");
}
@Override
protected void populate() {
populated = true;
}
@Override
public boolean canHandle(ActionContext context) {
return true;
}
}
} | false | platform_src_test_java_gov_nasa_arc_mct_gui_ActionManagerTest.java |
927 | public static class TestContextAwareAction extends ContextAwareAction {
protected TestContextAwareAction() {
super("abc");
putValue(Action.ACTION_COMMAND_KEY, "key");
}
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
}
@Override
public boolean canHandle(ActionContext context) {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
} | false | platform_src_test_java_gov_nasa_arc_mct_gui_ActionManagerTest.java |
928 | public static class TestContextAwareMenu extends ContextAwareMenu {
private static final long serialVersionUID = 1L;
public boolean populated = false;
public TestContextAwareMenu() {
super("test");
}
@Override
protected void populate() {
populated = true;
}
@Override
public boolean canHandle(ActionContext context) {
return true;
}
} | false | platform_src_test_java_gov_nasa_arc_mct_gui_ActionManagerTest.java |
929 | @SuppressWarnings("serial")
public abstract class CompositeAction extends ContextAwareAction {
private Action[] actions;
/**
* The constructor that takes a {@link String} paramater for the name of this action.
* @param name the name of this action.
*/
protected CompositeAction(String name) {
super(name);
}
/**
* This method returns a set of actions that will replace this {@link CompositeAction}.
* @return an array of {@link Action}s.
*/
public final Action[] getActions() {
return actions;
}
/**
* This method sets the set of actions to be replaced for this {@link CompositeAction}.
* @param actions an array of {@link Action}s.
*/
protected final void setActions(Action[] actions) {
this.actions = actions;
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_CompositeAction.java |
930 | public interface CompositeViewManifestationProvider extends ViewProvider {
/**
* Get the housed manifestations provided by this composite provider.
* @return a collection of view manifestations.
*/
public Collection<ViewProvider> getHousedManifestationProviders();
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_CompositeViewManifestationProvider.java |
931 | @SuppressWarnings("serial")
public abstract class ContextAwareAction extends AbstractAction {
/**
* Used in the client property to indicate border style for this action when appeared as a menu item.
*/
public static final String BORDER = "Border"; // Store value of type javax.swing.Border
/**
* Used in the client property to indicate the preferred size for this action when appeared as a menu item.
*/
public static final String PREFERRED_SIZE = "Preferred Size"; // Store value of type java.awt.Dimension
/**
* The constructor that takes a {@link String} parameter for the name of this action.
* @param name the name of this action
*/
protected ContextAwareAction(String name) {
super();
putValue(Action.NAME, name);
putValue(BORDER, BorderFactory.createEmptyBorder());
}
/**
* Given the {@link ActionContext}, this method determines the availability
* (i.e., either shown or hidden) of this action when appearing as a menu item.
* @param context the {@link ActionContext}
* @return a boolean that indicates the availability of the action
*/
public abstract boolean canHandle(ActionContext context);
/**
* This method determines the visibility (i.e., is enabled or disabled) of
* this action when appeared as a menu item.
* @return a boolean that indicates the availability of the action
*/
@Override
public abstract boolean isEnabled();
/**
* This method should be overridden with the implementation that performs this action.
* @param e the {@link ActionEvent}
*/
@Override
public abstract void actionPerformed(ActionEvent e);
/**
* This method should be invoked if persistence must take place before the end of the
* {@link #actionPerformed(ActionEvent)} method.
*/
public void completeWorkUnit() {
PlatformAccess.getPlatform().getPersistenceProvider().completeRelatedOperations(true);
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_ContextAwareAction.java |
932 | @SuppressWarnings("serial")
public abstract class ContextAwareMenu extends JMenu {
private List<MenuSection> sections;
private Map<String, MenuSection> map;
private String[] menubarPathAdditions;
private static final String[] EMPTY_STRING_ARRAY = new String[0];
/**
* The constructor that takes a {@link String} parameter for the text of this menu.
* @param text the text appears in the menu
*/
public ContextAwareMenu(String text) {
this(text, EMPTY_STRING_ARRAY);
}
/**
* The constructor that takes a name for this menu and an array of menubar paths.
* These menubar paths define the extension points of this menu.
* @param text the text that appears in the menu
* @param additions an array of menubar paths of type @{link String}
*/
public ContextAwareMenu(String text, String[] additions) {
super(text);
this.menubarPathAdditions = additions;
}
/**
* This method returns an array of menubar paths for extended menus and/or menu items.
* @return array of strings of the menu path additions that is non-null.
*/
public final String[] getExtensionMenubarPaths() {
return menubarPathAdditions;
}
/**
* This method returns a list of @{link {@link MenuSection} defined in this {@link ContextAwareMenu}.
* @return a {@link List} of non-null sections
*/
public List<MenuSection> getMenuSections() {
return sections == null ? Collections.<MenuSection>emptyList() : Collections.unmodifiableList(sections);
}
/**
* This method associates a collection of {@link MenuItemInfo} to the menubarPath.
* @param menubarPath the menubar path
* @param infos a {@link Collection} of {@link MenuItemInfo}
*/
public final void addMenuItemInfos(String menubarPath, Collection<MenuItemInfo> infos) {
if (map == null)
map = new HashMap<String, MenuSection>();
if (sections == null)
sections = new ArrayList<MenuSection>();
MenuSection section = map.get(menubarPath);
if (section == null) {
section = new MenuSection(menubarPath);
map.put(menubarPath, section);
sections.add(section);
}
for (MenuItemInfo info : infos)
section.addMenuItemInfo(info);
}
/**
* Given an {@link ActionContext}, this method determines the availability
* (i.e., either shown or hidden) of this menu.
* @param context the context
* @return a boolean that indicates the menu's visibility. Returns false by default.
*/
public boolean canHandle(ActionContext context) {
return false;
}
/**
* This method initializes the {@link MenuSection}s and {@link MenuItemInfo}s
* defined in this {@link ContextAwareMenu} by invoking {@link #populate()}, which is
* overridden by subclasses of {@link ContextAwareMenu}.
*/
public final void initialize() {
if (sections != null)
return;
populate();
}
/**
* This method is overridden by subclasses and should invoke
* {@link #addMenuItemInfos(String, Collection)} that associates a collection of
* {@link MenuItemInfo} to a menubar path..
*/
protected abstract void populate();
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_ContextAwareMenu.java |
933 | public class ExtendedPropertiesTest {
private ExtendedProperties ep;
@BeforeMethod
void setup() {
ep = new ExtendedProperties();
}
@Test
public void testExtendedPropertiesClone() {
final String stringKey = "stringKey";
final String stringValue = "stringValue";
final String viewManifestationKey = "viewManifestationValue";
final String viewValue = "newView";
ep.setProperty(stringKey, stringValue);
MCTViewManifestationInfo info = new MCTViewManifestationInfoImpl();
info.setManifestedViewType(viewValue);
ep.setProperty(viewManifestationKey, info);
ExtendedProperties clonedEp = ep.clone();
MCTViewManifestationInfo clonedInfo = clonedEp.getProperty(viewManifestationKey, MCTViewManifestationInfo.class);
Assert.assertNotSame(info, clonedInfo);
Assert.assertEquals(viewValue, clonedInfo.getManifestedViewType());
Assert.assertEquals(stringValue, clonedEp.getProperty(stringKey, String.class));
}
@Test(expectedExceptions={RuntimeException.class})
public void testExtendedPropertiesCloneCycle() {
final String viewManifestationKey = "viewManifestationValue";
final String viewValue = "newView";
MCTViewManifestationInfo info = new MCTViewManifestationInfoImpl();
info.setManifestedViewType(viewValue);
info.getOwnedProperties().add(ep);
ep.setProperty(viewManifestationKey, info);
ep.clone();
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_ExtendedPropertiesTest.java |
934 | class FeedCycleRenderer extends SwingWorker<Map<String, List<Map<String, String>>>, Map<String, List<Map<String, String>>>> {
private static final MCTLogger LOGGER = MCTLogger.getLogger(FeedCycleRenderer.class);
private static final MCTLogger PERF_LOGGER = MCTLogger
.getLogger("gov.nasa.arc.mct.performance.feeds.pool");
private final Set<FeedView> activeFeedViews;
private final Map<FeedProvider, Long[]> times;
private final ElapsedTimer dataRequestTimer = new ElapsedTimer();
private final ElapsedTimer uiRenderingTimer = new ElapsedTimer();
/**
* Create a new instance of a worker to retrieve and render feed data.
*
* @param timeMapping
* currently in the request set for the feed providers.
* @param activeViews
* views current maintained
*
*/
public FeedCycleRenderer(Map<FeedProvider, Long[]> timeMapping,
Set<FeedView> activeViews) {
activeFeedViews = activeViews;
times = timeMapping;
}
/**
* Returns the list of the feed providers from a manifestation. The default
* implementation invokes
* {@link FeedView#getVisibleFeedProviders()}.
*
* @param manifestation
* to retrieve feed providers from
* @return set of feed providers to retrieve data for
*/
protected Collection<FeedProvider> getProviders(FeedView manifestation) {
return manifestation.getVisibleFeedProviders();
}
/**
* Group the requests by the specified time mapping. Overriding methods should delegate to this method and then operate on the returned map.
* @return the batched set of requests.
*/
protected Map<Request, Set<FeedProvider>> batchByRequestTime() {
// build a set of feed providers
Set<FeedProvider> allProviders = new HashSet<FeedProvider>();
for (FeedView manifestation : activeFeedViews) {
allProviders.addAll(getProviders(manifestation));
}
// build a list of requests by time
Map<Request, Set<FeedProvider>> feedRequests = new HashMap<Request, Set<FeedProvider>>();
for (FeedProvider provider : allProviders) {
try {
Long[] timeMap = times.get(provider);
if (timeMap == null) {
continue;
}
Request r = new Request(timeMap[0], timeMap[1]);
Set<FeedProvider> ids = feedRequests.get(r);
if (ids == null) {
ids = new HashSet<FeedProvider>();
feedRequests.put(r, ids);
}
ids.add(provider);
} catch (Exception e) {
LOGGER.error("exception occurred while creating a request for " + provider, e);
}
}
return feedRequests;
}
/**
* This method provides the ability to make requests which are a subset of the full request.
* @param fullSpanRequests the set of requests initially issued with the full request span. This list may be mutated.
* @param lastRequests the last set of requests issued
* @return the requests for this iteration
*/
protected Map<Request, Set<FeedProvider>> getCurrentIterationRequests(final Map<Request, Set<FeedProvider>> fullSpanRequests,
final Map<Request, Set<FeedProvider>> lastRequests) {
return lastRequests.isEmpty() ? fullSpanRequests:Collections.<Request,Set<FeedProvider>>emptyMap();
}
@Override
protected Map<String, List<Map<String, String>>> doInBackground() {
dataRequestTimer.startInterval();
Map<String, List<Map<String, String>>> values = new HashMap<String, List<Map<String, String>>>();
PERF_LOGGER.debug("size of feed views {0}", activeFeedViews.size());
try {
final Map<Request, Set<FeedProvider>> fullSpanRequests = batchByRequestTime();
Map<Request, Set<FeedProvider>> currentIterationRequests = getCurrentIterationRequests(fullSpanRequests,Collections.<Request,Set<FeedProvider>>emptyMap());
while (!currentIterationRequests.isEmpty()) {
Set<Entry<Request, Set<FeedProvider>>> entries = currentIterationRequests.entrySet();
for (Entry<Request, Set<FeedProvider>> request : entries) {
if (isCancelled()) {
return Collections.emptyMap();
}
Request r = request.getKey();
Set<String> feedIds = new HashSet<String>();
for (FeedProvider provider : request.getValue()) {
try {
feedIds.add(provider.getSubscriptionId());
} catch (Exception e) {
LOGGER.error("exception occurred while getting subscription id from "
+ provider, e);
}
}
FeedAggregator feedAggregator = PlatformAccess.getPlatform().getFeedAggregator();
Map<String, List<Map<String, String>>> data = new HashMap<String, List<Map<String, String>>>();
if (feedAggregator != null) {
data = feedAggregator.getData(feedIds, TimeUnit.MILLISECONDS, r.getStartTime(), r.getEndTime());
}
Map<String, List<Map<String,String>>> adjValues = adjustResponses(data, r.getStartTime());
values.putAll(adjValues);
requestCompleted(values, r.getStartTime(), r.getEndTime());
}
currentIterationRequests = getCurrentIterationRequests(fullSpanRequests, currentIterationRequests);
}
} catch (Exception e) {
LOGGER.error("exception occurred while retrieving data ", e);
}
additionalBackgroundProcessing(values);
dataRequestTimer.stopInterval();
return values;
}
/**
* Iterate through the set of response values to ensure that times which are earlier than the specific time are
* moved to the current time.
* @param values returned from the invocation
* @param startTime for the request, values which are less than the request time will be adjusted to reflect this time.
*/
private Map<String, List<Map<String,String>>> adjustResponses(Map<String, List<Map<String,String>>> values, long startTime) {
for (Entry<String, List<Map<String,String>>> entry: values.entrySet()) {
// adjust the time for the initial value to be the maximum of the time in the value or the request start time
List<Map<String,String>> dataValues = entry.getValue();
// only adjust the value for a request that returns a single data point as this could be the case where the
// time of the data point is less than the start time, if so then shift the request time to be the value at the
// start time
if (dataValues.size() >= 1) {
Map<String, String> value = dataValues.get(0);
Long l = Long.parseLong(value.get(FeedProvider.NORMALIZED_TIME_KEY));
if (l < startTime) {
ArrayList<Map<String,String>> dataValues2 = new ArrayList<Map<String,String>>(dataValues);
Map<String, String> value2 = new HashMap<String, String>(value);
value2.put(FeedProvider.NORMALIZED_TIME_KEY, Long.toString(startTime));
dataValues2.set(0, value2);
entry.setValue(dataValues2);
}
}
}
return values;
}
/**
* Perform additional background processing before rendering the data.
*
* @param values
* to mutate if necessary prior to rendering the data.
*/
protected void additionalBackgroundProcessing(Map<String, List<Map<String, String>>> values) {
}
/**
* Perform background processing on each request before going to the next request. The overriding
* implementation is responsible for adjusting the data structure if necessary. For example, if
* the implementation is going to be incremental dispatching, using {@link #publish(Object...)}, then
* the values dispatched should be cleared before the method returns.
* @param values that have currently been retrieved.
* @param startTime used for values
* @param endTime used for values
*/
protected void requestCompleted(Map<String, List<Map<String, String>>> values, long startTime, long endTime) {
}
/**
* Return the requests that should be generated from the existing request list. The expected overriding
* of this method is for expanding the number of requests (chunking), such that the number of requests
* increases, but the size of each request decreases. This can help reduce the amount of memory for
* burst requests.
* @param requests the current set of requests
* @return the possibly expanded set of requests
*/
protected Map<Request, Set<FeedProvider>> adjustRequests(Map<Request, Set<FeedProvider>> requests) {
return requests;
}
@Override
protected void process(List<Map<String, List<Map<String, String>>>> chunks) {
if (isCancelled()) {
LOGGER.debug("swing worker cancel detected in process method");
return;
}
LOGGER.debug("Chunks size {0}", chunks.size());
for (Map<String, List<Map<String, String>>> chunk:chunks) {
dispatchDataToFeeds(chunk);
}
PERF_LOGGER.debug(
"feed cycle performance: data retrieval {0}, ui rendering {1}, total {2}",
dataRequestTimer.getIntervalInMillis(), uiRenderingTimer
.getIntervalInMillis(), dataRequestTimer
.getIntervalInMillis()
+ uiRenderingTimer.getIntervalInMillis());
}
@Override
protected void done() {
if (isCancelled()) {
LOGGER.debug("swing worker cancel detected in done method");
return;
}
renderFeeds();
PERF_LOGGER.debug(
"feed cycle performance: data retrieval {0}, ui rendering {1}, total {2}",
dataRequestTimer.getIntervalInMillis(), uiRenderingTimer
.getIntervalInMillis(), dataRequestTimer
.getIntervalInMillis()
+ uiRenderingTimer.getIntervalInMillis());
}
/**
* Returns the data obtained in the background thread.
*
* @return data obtained in the background thread.
*/
Map<String, List<Map<String, String>>> getData() throws InterruptedException,
ExecutionException {
return get();
}
/**
* Invoked when data has been acquired and is ready for rendering.
*
* @param manifestation
* pass the results to
* @param data
* retrieved from the feed
*/
protected void dispatchToFeed(FeedView manifestation,
Map<String, List<Map<String, String>>> data) {
manifestation.updateFromFeed(data);
}
private void dispatchDataToFeeds(Map<String, List<Map<String, String>>> data) {
uiRenderingTimer.startInterval();
for (FeedView fvm : activeFeedViews) {
try {
dispatchToFeed(fvm, data);
} catch (Exception e) {
LOGGER.error("exception occurred while invoking updateFromFeed " + fvm, e);
}
}
uiRenderingTimer.stopInterval();
}
void renderFeeds() {
try {
Map<String, List<Map<String, String>>> data = getData();
dispatchDataToFeeds(data);
} catch (Exception e) {
LOGGER.error("get generated exception, this indicates a problem in the platform", e);
}
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedCycleRenderer.java |
935 | public class FeedCycleRendererTest {
@Mock
private FeedView fv1;
@Mock
private FeedView fv2;
@Mock
private FeedView fv3;
@Mock
private FeedView fv4;
@Mock
private FeedView fv5;
@Mock
private FeedProvider numericProvider;
@Mock
private FeedProvider alphaProvider;
@Mock
private FeedProvider exceptionProvider;
private Map<String, List<Map<String,String>>> expectedValues;
private List<Map<String,String>> singleValue;
@Mock
private Platform platform;
@BeforeMethod
public void initialize() {
MockitoAnnotations.initMocks(this);
Mockito.when(fv1.getVisibleFeedProviders()).thenReturn(Collections.singleton(numericProvider));
Mockito.when(fv2.getVisibleFeedProviders()).thenReturn(Collections.singleton(alphaProvider));
Mockito.when(fv3.getVisibleFeedProviders()).thenReturn(Collections.singleton(exceptionProvider));
Mockito.when(fv4.getVisibleFeedProviders()).thenReturn(Collections.singleton(numericProvider));
Mockito.when(fv5.getVisibleFeedProviders()).thenReturn(Collections.<FeedProvider>emptySet());
expectedValues = new HashMap<String, List<Map<String,String>>>();
Map<String,String> singleValueMap = new HashMap<String,String>();
singleValueMap.put(FeedProvider.NORMALIZED_TIME_KEY, "1000");
singleValue = Collections.singletonList(singleValueMap);
expectedValues.put("numeric", singleValue);
expectedValues.put("alpha", singleValue);
Mockito.when(numericProvider.getSubscriptionId()).thenReturn("numeric");
Mockito.when(alphaProvider.getSubscriptionId()).thenReturn("alpha");
Mockito.when(exceptionProvider.getSubscriptionId()).thenReturn("exception");
Mockito.when(platform.getFeedAggregator()).thenReturn(new FeedAggregator() {
@Override
public Map<String, List<Map<String, String>>> getData(Set<String> feedIDs, TimeUnit timeUnit,
long startTime, long endTime) {
return expectedValues;
}
});
new PlatformAccess().setPlatform(platform);
}
@AfterMethod
public void tearDown() {
new PlatformAccess().releasePlatform();
}
@Test
public void testAdjustResponse() throws Exception {
Map<FeedProvider, Long[]> times = new HashMap<FeedProvider, Long[]>();
FeedCycleRenderer worker = new FeedCycleRenderer(times, Collections.<FeedView>singleton(fv1)) {
@Override
public Map<String, List<Map<String,String>>> doInBackground() {
return super.doInBackground();
}
};
Method m = worker.getClass().getSuperclass().getDeclaredMethod("adjustResponses", Map.class, Long.TYPE);
long startTime = 1000;
Map<String, List<Map<String,String>>> values = new HashMap<String, List<Map<String,String>>>();
values.put("1", Collections.singletonList(Collections.singletonMap(FeedProvider.NORMALIZED_TIME_KEY, Long.toString(startTime-1))));
values.put("2", Collections.singletonList(Collections.singletonMap(FeedProvider.NORMALIZED_TIME_KEY, Long.toString(startTime+1))));
m.setAccessible(true);
m.invoke(worker, values, startTime);
Assert.assertEquals(values.get("1").get(0).get(FeedProvider.NORMALIZED_TIME_KEY), Long.toString(startTime));
Assert.assertEquals(values.get("2").get(0).get(FeedProvider.NORMALIZED_TIME_KEY), Long.toString(startTime+1));
}
@Test
public void testDoInBackground() throws Exception {
Map<FeedProvider, Long[]> times = new HashMap<FeedProvider, Long[]>();
times.put(numericProvider, new Long[]{0L,1L});
times.put(alphaProvider, new Long[]{0L,1L});
times.put(exceptionProvider, new Long[]{0L,1L});
FeedCycleRenderer worker = new FeedCycleRenderer(times, Collections.<FeedView>singleton(fv1)) {
@Override
public Map<String, List<Map<String,String>>> doInBackground() {
return super.doInBackground();
}
};
worker.cancel(true);
Assert.assertTrue(worker.doInBackground().isEmpty());
worker = new FeedCycleRenderer(times, new HashSet<FeedView>(Arrays.asList(fv1, fv2, fv3, fv4, fv5))) {
@Override
public Map<String, List<Map<String,String>>> doInBackground() {
return super.doInBackground();
}
};
Map<String, List<Map<String,String>>> values = worker.doInBackground();
Assert.assertEquals(values.size(), expectedValues.size());
for (String key:expectedValues.keySet()) {
Assert.assertTrue(values.containsKey(key));
}
Assert.assertEquals(1, values.get(numericProvider.getSubscriptionId()).size());
Assert.assertEquals(1, values.get(alphaProvider.getSubscriptionId()).size());
Assert.assertNull(values.get(exceptionProvider.getSubscriptionId()));
worker.cancel(true);
worker.done();
}
@SuppressWarnings("unchecked")
@Test
public void testDone() throws Exception {
Map<FeedProvider, Long[]> times = new HashMap<FeedProvider, Long[]>();
// setup an exception during rendering to make an exception in the platform won't blog future
// rendering cycles
FeedCycleRenderer worker = new FeedCycleRenderer(times, new HashSet<FeedView>(Arrays.asList(fv1, fv2, fv3))) {
@Override
Map<String, List<Map<String, String>>> getData() throws InterruptedException, ExecutionException {
throw new RuntimeException();
}
};
worker.done();
FeedView exManifestation = Mockito.mock(FeedView.class);
Mockito.doThrow(new RuntimeException()).when(exManifestation).updateFromFeed(Mockito.anyMap());
FeedView goodManifestation = Mockito.mock(FeedView.class);
worker = new FeedCycleRenderer(times, new HashSet<FeedView>(Arrays.asList(exManifestation, goodManifestation))) {
@Override
Map<String, List<Map<String, String>>> getData() throws InterruptedException, ExecutionException {
return Collections.emptyMap();
}
};
worker.done();
Mockito.verify(exManifestation).updateFromFeed(Mockito.anyMap());
Mockito.verify(goodManifestation).updateFromFeed(Mockito.anyMap());
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedCycleRendererTest.java |
936 | Mockito.when(platform.getFeedAggregator()).thenReturn(new FeedAggregator() {
@Override
public Map<String, List<Map<String, String>>> getData(Set<String> feedIDs, TimeUnit timeUnit,
long startTime, long endTime) {
return expectedValues;
}
}); | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedCycleRendererTest.java |
937 | FeedCycleRenderer worker = new FeedCycleRenderer(times, Collections.<FeedView>singleton(fv1)) {
@Override
public Map<String, List<Map<String,String>>> doInBackground() {
return super.doInBackground();
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedCycleRendererTest.java |
938 | FeedCycleRenderer worker = new FeedCycleRenderer(times, Collections.<FeedView>singleton(fv1)) {
@Override
public Map<String, List<Map<String,String>>> doInBackground() {
return super.doInBackground();
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedCycleRendererTest.java |
939 | worker = new FeedCycleRenderer(times, new HashSet<FeedView>(Arrays.asList(fv1, fv2, fv3, fv4, fv5))) {
@Override
public Map<String, List<Map<String,String>>> doInBackground() {
return super.doInBackground();
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedCycleRendererTest.java |
940 | FeedCycleRenderer worker = new FeedCycleRenderer(times, new HashSet<FeedView>(Arrays.asList(fv1, fv2, fv3))) {
@Override
Map<String, List<Map<String, String>>> getData() throws InterruptedException, ExecutionException {
throw new RuntimeException();
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedCycleRendererTest.java |
941 | worker = new FeedCycleRenderer(times, new HashSet<FeedView>(Arrays.asList(exManifestation, goodManifestation))) {
@Override
Map<String, List<Map<String, String>>> getData() throws InterruptedException, ExecutionException {
return Collections.emptyMap();
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedCycleRendererTest.java |
942 | public final class FeedManagerImpl implements FeedManager {
private static FeedManagerImpl INSTANCE = new FeedManagerImpl();
private FeedManagerImpl() {
}
/**
* Returns the feed manager instance.
* @return implementation of feed manager
*/
public static FeedManager getInstance() {
return INSTANCE;
}
@Override
public void clear() {
Set<FeedView> allFeedManifestations = FeedView.getAllActiveFeedManifestations();
for (FeedView feedViewManifestation: allFeedManifestations) {
feedViewManifestation.clear(feedViewManifestation.getVisibleFeedProviders());
}
FeedView.resetLastDataRequestTimeToCurrentTime();
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedManagerImpl.java |
943 | class FeedRenderingPool {
private final Timer timer;
private final int paintRate; // milliseconds between updating feed views
/**
* This variable determines the currently active subscriptions and will only be accessed
* from the timer thread; hence, no synchronization is required.
*/
private Set<FeedProvider> activeSubscriptions = Collections.emptySet();
private final Set<FeedView> activeFeedViews = new ConcurrentSkipListSet<FeedView>(new IdentityComparator());
private static final MCTLogger LOGGER = MCTLogger.getLogger(FeedRenderingPool.class);
private final AtomicInteger activeRenderers = new AtomicInteger(0);
private static final int MAX_ACTIVE_REQUESTS = 1;
private final ConcurrentHashMap<FeedProvider, Long> activeFeeds = new ConcurrentHashMap<FeedProvider, Long>();
private final AtomicReference<SynchronizationControl> activeSyncControl = new AtomicReference<SynchronizationControl>();
private AtomicBoolean exceededMaxSubscriptions = new AtomicBoolean(false);
private static final int maxSubscriptions = initMaxSubscriptions();
private static final Comparator<FeedProvider> FEED_COMPARATOR = new Comparator<FeedProvider>() {
@Override
public int compare(FeedProvider o1, FeedProvider o2) {
return o1.getSubscriptionId().compareTo(o2.getSubscriptionId());
}
};
/**
* Create a new instance.
* @param paintRateInterval how often in milliseconds to paint the feed displays
* @throws IllegalArgumentException if paintRateIntervalue is < 1
*/
public FeedRenderingPool(int paintRateInterval) throws IllegalArgumentException {
if (paintRateInterval < 1) {
throw new IllegalArgumentException("paint rate interval must be greater than 0");
}
paintRate = paintRateInterval;
timer = new Timer("MCT Painting timer",true);
TimerTask task = new TimerTask() {
@Override
public void run() {
LOGGER.debug("timer event fired");
try {
startWorker();
} catch (Exception e) {
LOGGER.error("exception thrown out of scheduled paint thread. " +
"The root cause of this exception should be fixed but operation should continue normally", e);
}
}
};
timer.scheduleAtFixedRate(task, paintRate, paintRate);
}
private static class IdentityComparator implements Comparator<Object>, Serializable {
private static final long serialVersionUID = 1L;
@Override
public int compare(Object o1, Object o2) {
return System.identityHashCode(o2) - System.identityHashCode(o1);
}
}
void cancelTimer() {
timer.cancel();
}
/**
* Add a view to list of feeds being rendered on the paint cycle.
* @param manifestation to start delivering feed events to
*/
public void addFeedView(FeedView manifestation) throws IllegalArgumentException {
activeFeedViews.add(manifestation);
}
/**
* Add a view to list of feeds being rendered on the paint cycle.
* @param manifestation to stop delivering feed events to
*/
public void removeFeedView(FeedView manifestation) {
activeFeedViews.remove(manifestation);
}
public SynchronizationControl synchronizeTime(final long syncTime) {
final Set<FeedView> syncedManifestations = new HashSet<FeedView>();
SynchronizationControl sc = new SynchronizationControl() {
@Override
public void update(long syncTime) {
/* Assume the "time" is uniform across all providers, this is a limitation that needs to
* removed when feeds (non ISP) are added. One way to do this is to pass the time
* service along with the time to get offsets between the various time services. For
* example, TimeServiceA - 4, TimeServiceB - 2, then if time 3 was passed along with
* TimeServiceA then the offset to TimeServiceB would be (2 - 4) = -2 + time to get the
* time from TimeServiceB.
*/
Map<FeedProvider, Long[]> times = new HashMap<FeedProvider,Long[]>();
for (FeedView manifestation:activeFeedViews) {
for (FeedProvider provider:manifestation.getVisibleFeedProviders()) {
times.put(provider, new Long[]{syncTime-2000, syncTime});
}
}
FeedCycleRenderer renderer = createSyncWorker(syncTime, times, activeFeedViews, syncedManifestations);
try {
renderer.execute();
} catch (Exception e) {
LOGGER.error(e);
}
}
@Override
public void synchronizationDone() {
activeSyncControl.set(null);
for(FeedView m : syncedManifestations) {
m.synchronizationDone();
}
}
};
if (!activeSyncControl.compareAndSet(null, sc)) {
return null;
}
/* Assume the "time" is uniform across all providers, this is a limitation that needs to
* removed when feeds (non ISP) are added. One way to do this is to pass the time
* service along with the time to get offsets between the various time services. For
* example, TimeServiceA - 4, TimeServiceB - 2, then if time 3 was passed along with
* TimeServiceA then the offset to TimeServiceB would be (2 - 4) = -2 + time to get the
* time from TimeServiceB.
*/
Map<FeedProvider, Long[]> times = new HashMap<FeedProvider,Long[]>();
for (FeedView manifestation:activeFeedViews) {
for (FeedProvider provider:manifestation.getVisibleFeedProviders()) {
times.put(provider, new Long[]{syncTime-2000, syncTime});
}
}
FeedCycleRenderer renderer = createSyncWorker(syncTime, times, activeFeedViews, syncedManifestations);
try {
renderer.execute();
} catch (Exception e) {
LOGGER.error(e);
sc.synchronizationDone();
sc = null;
}
return sc;
}
FeedCycleRenderer createSyncWorker(final long syncTime, Map<FeedProvider, Long[]> times, Set<FeedView> activeFeedViews, final Set<FeedView> syncedManifestations) {
return new FeedCycleRenderer(times,activeFeedViews) {
@Override
protected void dispatchToFeed(FeedView manifestation,
Map<String, List<Map<String, String>>> data) {
syncedManifestations.add(manifestation);
manifestation.synchronizeTime(data,syncTime);
}
};
}
FeedCycleRenderer createWorker(Map<FeedProvider, Long[]> times, Set<FeedView> activeFeedViews) {
return new FeedCycleRenderer(times, activeFeedViews);
}
/**
* Start a new worker or extend an existing worker. This will only be called from the
* timer thread.
*/
private void startWorker() {
handleSubscriptions();
// if the current number of active requests > max number of threads, then wait for the next
// one
if (activeRenderers.get() < MAX_ACTIVE_REQUESTS && activeSyncControl.get() == null) {
Map<TimeService,Long> currentTimes = new HashMap<TimeService,Long>();
Map<FeedProvider,Long[]> times = new TreeMap<FeedProvider,Long[]>(FEED_COMPARATOR);
for (Entry<FeedProvider,Long> lastTimeMapping:activeFeeds.entrySet()) {
FeedProvider feed = lastTimeMapping.getKey();
long lastRequestTime = lastTimeMapping.getValue();
// ensure that all values coming from the same time service reflect the same time
Long cachedTime = currentTimes.get(feed.getTimeService());
if (cachedTime == null) {
cachedTime = feed.getTimeService().getCurrentTime();
currentTimes.put(feed.getTimeService(), cachedTime);
}
long currentTime = cachedTime;
Long[] timeRange = new Long[] {lastRequestTime, currentTime};
if (timeRange[0] < timeRange[1]) {
timeRange[0]++;
times.put(feed, timeRange);
activeFeeds.put(feed, currentTime);
}
}
if (!times.isEmpty()) {
FeedCycleRenderer worker = createWorker(times, activeFeedViews);
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
activeRenderers.decrementAndGet();
}
}
});
activeRenderers.incrementAndGet();
worker.execute();
}
}
}
/**
* Determine the current subscriptions required by iterating through the active manifestations
* and extracting the providers.
* @return
*/
private Set<FeedProvider> buildRequiredSubscriptions() {
Set<FeedProvider> requiredSubscriptions = new TreeSet<FeedProvider>(FEED_COMPARATOR);
for (FeedView manifestation: activeFeedViews) {
Collection<FeedProvider> providers = manifestation.getVisibleFeedProviders();
if (providers != null) {
requiredSubscriptions.addAll(providers);
}
}
return requiredSubscriptions;
}
SubscriptionManager getSubscriptionManager() {
return PlatformAccess.getPlatform().getSubscriptionManager();
}
/**
* Use the subscription manager to manage subscriptions
*/
void handleSubscriptions() {
Set<FeedProvider> requiredSubscriptions = buildRequiredSubscriptions();
List<FeedProvider> newSubscriptions = new ArrayList<FeedProvider>();
List<FeedProvider> removedSubscriptions = new ArrayList<FeedProvider>();
Set<FeedProvider> set = new TreeSet<FeedProvider>(FEED_COMPARATOR);
set.addAll(requiredSubscriptions);
ComponentModelUtil.computeAsymmetricSetDifferences(
requiredSubscriptions, activeSubscriptions, newSubscriptions, removedSubscriptions,set);
if (exceededMaxSubscriptions(requiredSubscriptions, newSubscriptions)) return;
SubscriptionManager manager = getSubscriptionManager();
if (manager != null) {
for (FeedProvider feed:removedSubscriptions) {
LOGGER.debug("removing subscription for {0}", feed.getSubscriptionId());
manager.unsubscribe(feed.getSubscriptionId());
activeFeeds.remove(feed);
}
List<String> newlyAddedSubscriptionIds = new ArrayList<String> (newSubscriptions.size());
for (FeedProvider feed:newSubscriptions) {
LOGGER.debug("adding subscription for {0}", feed.getSubscriptionId());
newlyAddedSubscriptionIds.add(feed.getSubscriptionId());
activeFeeds.put(feed, feed.getTimeService().getCurrentTime());
}
assert newlyAddedSubscriptionIds.size() == newSubscriptions.size();
if (!newlyAddedSubscriptionIds.isEmpty()) {
manager.subscribe(newlyAddedSubscriptionIds.toArray(new String[newlyAddedSubscriptionIds.size()]));
}
activeSubscriptions = requiredSubscriptions;
} else {
LOGGER.warn("subscription manager not available, subscriptions not updated");
}
}
private boolean exceededMaxSubscriptions(Set<FeedProvider> requiredSubscriptions,
List<FeedProvider> newSubscriptions) {
if (requiredSubscriptions.size() > maxSubscriptions && !newSubscriptions.isEmpty()) {
if (exceededMaxSubscriptions.getAndSet(true) == false) {
LOGGER.error("You have exceeded the maximum number of active subscriptions configured for this application. \n The limit is " +maxSubscriptions+". Please remove some of your unused views.");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
OptionBox.showMessageDialog(
null,
"You have exceeded the maximum number of active subscriptions \nconfigured for this application. \nPlease remove some of your unused views.",
"Maximum subscriptions Error",
OptionBox.ERROR_MESSAGE);
}
});
}
return true;
} else {
exceededMaxSubscriptions.set(false);
return false;
}
}
private static int initMaxSubscriptions() {
int defaultMax = 3000;
int max = defaultMax;
final MCTProperties mctProperties = MCTProperties.DEFAULT_MCT_PROPERTIES;
String str = mctProperties.getProperty("max.subscriptions", "unset");
if (str.equals("unset")) {
LOGGER.error("Property mct.max.subscriptions is not set or empty. Using default of: "+ defaultMax);
}
try {
max = new Integer(str);
} catch (NumberFormatException e) {
LOGGER.error("Could not convert mct.max.subscriptions to a valid number. Using default of: "+ defaultMax);
}
return max;
}
Set<FeedView> getAllActiveFeedManifestations() {
if (activeFeedViews == null) { return Collections.emptySet(); }
return Collections.<FeedView>unmodifiableSet(activeFeedViews);
}
void resetLastDataRequestTimeToCurrentTime() {
for (Entry<FeedProvider, Long> entry : activeFeeds.entrySet()) {
entry.setValue(entry.getKey().getTimeService().getCurrentTime());
}
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedRenderingPool.java |
944 | private static final Comparator<FeedProvider> FEED_COMPARATOR = new Comparator<FeedProvider>() {
@Override
public int compare(FeedProvider o1, FeedProvider o2) {
return o1.getSubscriptionId().compareTo(o2.getSubscriptionId());
}
}; | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedRenderingPool.java |
945 | TimerTask task = new TimerTask() {
@Override
public void run() {
LOGGER.debug("timer event fired");
try {
startWorker();
} catch (Exception e) {
LOGGER.error("exception thrown out of scheduled paint thread. " +
"The root cause of this exception should be fixed but operation should continue normally", e);
}
}
}; | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedRenderingPool.java |
946 | SynchronizationControl sc = new SynchronizationControl() {
@Override
public void update(long syncTime) {
/* Assume the "time" is uniform across all providers, this is a limitation that needs to
* removed when feeds (non ISP) are added. One way to do this is to pass the time
* service along with the time to get offsets between the various time services. For
* example, TimeServiceA - 4, TimeServiceB - 2, then if time 3 was passed along with
* TimeServiceA then the offset to TimeServiceB would be (2 - 4) = -2 + time to get the
* time from TimeServiceB.
*/
Map<FeedProvider, Long[]> times = new HashMap<FeedProvider,Long[]>();
for (FeedView manifestation:activeFeedViews) {
for (FeedProvider provider:manifestation.getVisibleFeedProviders()) {
times.put(provider, new Long[]{syncTime-2000, syncTime});
}
}
FeedCycleRenderer renderer = createSyncWorker(syncTime, times, activeFeedViews, syncedManifestations);
try {
renderer.execute();
} catch (Exception e) {
LOGGER.error(e);
}
}
@Override
public void synchronizationDone() {
activeSyncControl.set(null);
for(FeedView m : syncedManifestations) {
m.synchronizationDone();
}
}
}; | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedRenderingPool.java |
947 | return new FeedCycleRenderer(times,activeFeedViews) {
@Override
protected void dispatchToFeed(FeedView manifestation,
Map<String, List<Map<String, String>>> data) {
syncedManifestations.add(manifestation);
manifestation.synchronizeTime(data,syncTime);
}
}; | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedRenderingPool.java |
948 | worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
activeRenderers.decrementAndGet();
}
}
}); | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedRenderingPool.java |
949 | SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
OptionBox.showMessageDialog(
null,
"You have exceeded the maximum number of active subscriptions \nconfigured for this application. \nPlease remove some of your unused views.",
"Maximum subscriptions Error",
OptionBox.ERROR_MESSAGE);
}
}); | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedRenderingPool.java |
950 | private static class IdentityComparator implements Comparator<Object>, Serializable {
private static final long serialVersionUID = 1L;
@Override
public int compare(Object o1, Object o2) {
return System.identityHashCode(o2) - System.identityHashCode(o1);
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedRenderingPool.java |
951 | public class FeedRenderingPoolTest {
private FeedRenderingPool pool;
@Mock
private FeedView fv1;
@Mock
private FeedProvider fp;
@Mock
private SubscriptionManager manager;
private volatile FeedCycleRendererTest activeRenderer;
private AtomicLong time;
private final AtomicReference<String> feedId1 = new AtomicReference<String>();
@Mock
private TimeService timeService;
@AfterMethod
public void terminate() throws Exception {
pool.cancelTimer();
if (activeRenderer != null) {
activeRenderer.cancel(true);
}
}
@BeforeMethod
public void initialize() throws Exception {
MockitoAnnotations.initMocks(this);
time = new AtomicLong(0);
Field f = FeedView.class.getDeclaredField("feedPool");
f.setAccessible(true);
FeedRenderingPool rp = (FeedRenderingPool) f.get(fv1);
rp.cancelTimer();
Mockito.when(fv1.getVisibleFeedProviders()).thenReturn(Collections.singleton(fp));
Mockito.when(fp.getSubscriptionId()).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return feedId1.get();
}
});
Mockito.when(fp.getTimeService()).thenReturn(timeService);
Mockito.when(fp.toString()).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return "fp : " + feedId1.get();
}
});
Mockito.when(timeService.getCurrentTime()).thenAnswer(new Answer<Long>() {
@Override
public Long answer(InvocationOnMock invocation) throws Throwable {
return time.getAndIncrement();
}
});
pool = new FeedRenderingPool(1000) {
@Override
FeedCycleRenderer createWorker(Map<FeedProvider, Long[]> timeMapping, Set<FeedView> activeFeedViews) {
return activeRenderer = new FeedCycleRendererTest(timeMapping, activeFeedViews);
}
@Override
FeedCycleRenderer createSyncWorker(long syncTime, Map<FeedProvider, Long[]> times,
Set<FeedView> activeFeedViews, Set<FeedView> syncedManifestations) {
return new SyncFeedCycleRenderer(times, activeFeedViews);
}
@Override
SubscriptionManager getSubscriptionManager() {
return manager;
}
};
activeRenderer = null;
}
static class SyncFeedCycleRenderer extends FeedCycleRenderer {
public SyncFeedCycleRenderer(Map<FeedProvider, Long[]> timeMappings,
Set<FeedView> activeViews) {
super(timeMappings,activeViews);
}
@Override
protected Map<String, List<Map<String,String>>> doInBackground() {
return new HashMap<String, List<Map<String,String>>>();
}
@Override
Map<String, List<Map<String, String>>> getData() throws InterruptedException, ExecutionException {
return Collections.emptyMap();
}
}
static class FeedCycleRendererTest extends FeedCycleRenderer {
private Semaphore lock = new Semaphore(1,true);
public FeedCycleRendererTest(Map<FeedProvider, Long[]> timeMappings,
Set<FeedView> activeViews) {
super(timeMappings,activeViews);
}
public Semaphore getSemaphore() {
return lock;
}
@Override
protected Map<String, List<Map<String,String>>> doInBackground() {
try {
lock.acquire();
} catch (InterruptedException ie) {}
return new HashMap<String, List<Map<String,String>>>();
}
@Override
protected void done() {
lock.release();
}
}
static class FeedCycleRendererTest2 extends FeedCycleRendererTest {
private Map<FeedProvider, Long[]> timeMappings;
public FeedCycleRendererTest2(Map<FeedProvider, Long[]> timeMappings,
Set<FeedView> activeViews) {
super(timeMappings,activeViews);
this.timeMappings = timeMappings;
}
@Override
protected Map<String, List<Map<String,String>>> doInBackground() {
Map<String, List<Map<String,String>>> values = new HashMap<String, List<Map<String, String>>>();
for (FeedProvider fp:timeMappings.keySet()) {
values.put(fp.getSubscriptionId(), Collections.<Map<String,String>>emptyList());
}
return values;
}
@Override
protected void done() {
}
}
@Test(expectedExceptions=IllegalArgumentException.class)
public void testIntervalChecking() {
new FeedRenderingPool(-1);
}
@Test
public void testSynchronizeTime() {
pool.addFeedView(fv1);
SynchronizationControl sc =
pool.synchronizeTime(System.currentTimeMillis() - 2);
Assert.assertNotNull(sc);
Assert.assertNull(pool.synchronizeTime(System.currentTimeMillis()));
sc.synchronizationDone();
Assert.assertNotNull(pool.synchronizeTime(System.currentTimeMillis()));
}
@Test
public void testAddFeedView() throws Exception {
pool.addFeedView(fv1);
Thread.sleep(750);
int maxCount = 15;
while (time.get() < 3 && maxCount-- > 0) {
Thread.yield();
Thread.sleep(100);
}
activeRenderer.getSemaphore().release();
activeRenderer.getSemaphore().acquire();
Assert.assertTrue(activeRenderer.isDone());
pool.removeFeedView(fv1);
}
@Test
public void testHandleSubscriptions() throws Exception {
pool.cancelTimer();
Field f = FeedView.class.getDeclaredField("feedPool");
f.setAccessible(true);
FeedRenderingPool rp = (FeedRenderingPool) f.get(fv1);
rp.cancelTimer();
final String feedId = "f1";
FeedView fv2 = Mockito.mock(FeedView.class);
FeedProvider fp2 = Mockito.mock(FeedProvider.class);
Mockito.when(fp2.getSubscriptionId()).thenReturn(feedId);
Mockito.when(fp2.toString()).thenReturn("fp2 : " + feedId);
Mockito.when(fp2.getTimeService()).thenReturn(timeService);
Mockito.when(fv2.getVisibleFeedProviders()).thenReturn(Collections.singleton(fp2));
feedId1.set(feedId);
Assert.assertEquals(fv1.getVisibleFeedProviders().iterator().next().getSubscriptionId(), feedId);
Assert.assertEquals(fv1.getVisibleFeedProviders().iterator().next().getSubscriptionId().compareTo(fv2.getVisibleFeedProviders().iterator().next().getSubscriptionId()),0);
pool.addFeedView(fv1);
pool.handleSubscriptions();
Mockito.verify(manager).subscribe(feedId);
pool.handleSubscriptions();
Mockito.verify(manager).subscribe(feedId);
pool.addFeedView(fv2);
pool.handleSubscriptions();
Mockito.verify(manager,Mockito.times(1)).subscribe(feedId);
pool.removeFeedView(fv1);
pool.removeFeedView(fv2);
pool.handleSubscriptions();
Mockito.verify(manager).unsubscribe(feedId);
}
@Test
public void testSubscriptionsExceeded() {
for (Window w: Window.getWindows()) {
w.setVisible(false);
w.dispose();
}
Assert.assertTrue(Window.getWindows().length == 0);
Collection<FeedProvider> providers = new ArrayList<FeedProvider>(3000);
for (int i = 0; i < 3001; i++) {
FeedProvider fp = Mockito.mock(FeedProvider.class);
Mockito.when(fp.getSubscriptionId()).thenReturn(Integer.toString(i));
providers.add(fp);
}
Mockito.when(fv1.getVisibleFeedProviders()).thenReturn(providers);
pool.cancelTimer();
pool = new FeedRenderingPool(10000) {
SubscriptionManager getSubscriptionManager() {
return manager;
}
@Override
FeedCycleRenderer createWorker(Map<FeedProvider, Long[]> timeMapping, Set<FeedView> activeFeedViews) {
return activeRenderer = new FeedCycleRendererTest(timeMapping, activeFeedViews);
}
};
pool.addFeedView(fv1);
pool.handleSubscriptions();
final AtomicBoolean invokedLater = new AtomicBoolean(false);
final AtomicBoolean dialogAppeared = new AtomicBoolean(false);
// verify that the max subscriptions exceeded dialog appears
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
int windowCount = 0;
for (Window w: Window.getWindows()) {
if (w instanceof JDialog) {
JDialog d = (JDialog) w;
String title = d.getTitle();
if (title.equals("Maximum subscriptions Error")) {
windowCount++;
}
d.setVisible(false);
d.dispose();
}
}
dialogAppeared.set(windowCount == 1);
invokedLater.set(true);
}
});
while (!invokedLater.get()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
Assert.assertTrue(dialogAppeared.get());
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
952 | Mockito.when(fp.getSubscriptionId()).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return feedId1.get();
}
}); | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
953 | Mockito.when(fp.toString()).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return "fp : " + feedId1.get();
}
}); | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
954 | Mockito.when(timeService.getCurrentTime()).thenAnswer(new Answer<Long>() {
@Override
public Long answer(InvocationOnMock invocation) throws Throwable {
return time.getAndIncrement();
}
}); | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
955 | pool = new FeedRenderingPool(1000) {
@Override
FeedCycleRenderer createWorker(Map<FeedProvider, Long[]> timeMapping, Set<FeedView> activeFeedViews) {
return activeRenderer = new FeedCycleRendererTest(timeMapping, activeFeedViews);
}
@Override
FeedCycleRenderer createSyncWorker(long syncTime, Map<FeedProvider, Long[]> times,
Set<FeedView> activeFeedViews, Set<FeedView> syncedManifestations) {
return new SyncFeedCycleRenderer(times, activeFeedViews);
}
@Override
SubscriptionManager getSubscriptionManager() {
return manager;
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
956 | pool = new FeedRenderingPool(10000) {
SubscriptionManager getSubscriptionManager() {
return manager;
}
@Override
FeedCycleRenderer createWorker(Map<FeedProvider, Long[]> timeMapping, Set<FeedView> activeFeedViews) {
return activeRenderer = new FeedCycleRendererTest(timeMapping, activeFeedViews);
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
957 | SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
int windowCount = 0;
for (Window w: Window.getWindows()) {
if (w instanceof JDialog) {
JDialog d = (JDialog) w;
String title = d.getTitle();
if (title.equals("Maximum subscriptions Error")) {
windowCount++;
}
d.setVisible(false);
d.dispose();
}
}
dialogAppeared.set(windowCount == 1);
invokedLater.set(true);
}
}); | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
958 | static class FeedCycleRendererTest extends FeedCycleRenderer {
private Semaphore lock = new Semaphore(1,true);
public FeedCycleRendererTest(Map<FeedProvider, Long[]> timeMappings,
Set<FeedView> activeViews) {
super(timeMappings,activeViews);
}
public Semaphore getSemaphore() {
return lock;
}
@Override
protected Map<String, List<Map<String,String>>> doInBackground() {
try {
lock.acquire();
} catch (InterruptedException ie) {}
return new HashMap<String, List<Map<String,String>>>();
}
@Override
protected void done() {
lock.release();
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
959 | static class FeedCycleRendererTest2 extends FeedCycleRendererTest {
private Map<FeedProvider, Long[]> timeMappings;
public FeedCycleRendererTest2(Map<FeedProvider, Long[]> timeMappings,
Set<FeedView> activeViews) {
super(timeMappings,activeViews);
this.timeMappings = timeMappings;
}
@Override
protected Map<String, List<Map<String,String>>> doInBackground() {
Map<String, List<Map<String,String>>> values = new HashMap<String, List<Map<String, String>>>();
for (FeedProvider fp:timeMappings.keySet()) {
values.put(fp.getSubscriptionId(), Collections.<Map<String,String>>emptyList());
}
return values;
}
@Override
protected void done() {
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
960 | static class SyncFeedCycleRenderer extends FeedCycleRenderer {
public SyncFeedCycleRenderer(Map<FeedProvider, Long[]> timeMappings,
Set<FeedView> activeViews) {
super(timeMappings,activeViews);
}
@Override
protected Map<String, List<Map<String,String>>> doInBackground() {
return new HashMap<String, List<Map<String,String>>>();
}
@Override
Map<String, List<Map<String, String>>> getData() throws InterruptedException, ExecutionException {
return Collections.emptyMap();
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedRenderingPoolTest.java |
961 | public abstract class FeedView extends View {
private static final long serialVersionUID = 1L;
private static final int PAINT_RATE = 250; // paint rate in milliseconds
private static final FeedRenderingPool feedPool = new FeedRenderingPool(PAINT_RATE);
/**
* The maximum number of data points that are returned from a data request. This will cause the
* requests to be split into a number of requests that the client will need to merge as they are completed.
*
*/
private static final int MAX_DATA_POINTS = 1000;
/**
* Adjust the rendering cycle based on the visibility of this component, if the component is visible
* then add to the rendering list if it is not, then remove it.
*/
private final AncestorListener ancestorListener = new AncestorListener() {
@Override
public void ancestorAdded(AncestorEvent event) {
feedPool.addFeedView(FeedView.this);
}
@Override
public void ancestorMoved(AncestorEvent event) {
}
@Override
public void ancestorRemoved(AncestorEvent event) {
feedPool.removeFeedView(FeedView.this);
}
};
/**
* Creates a new feed view manifestation with characteristics given by
* persisted view manifestation information.
*
* @param component the currently bound component
* @param info info for this component
*/
public FeedView(AbstractComponent component, ViewInfo info) {
super(component,info);
addAncestorListener(ancestorListener);
}
/**
* Creates a new feed view manifestation with characteristics given by
* persisted view manifestation information.
*
* @param ac the <code>AbstractComponent</code>
*/
public FeedView(AbstractComponent ac) {
addAncestorListener(ancestorListener);
}
/**
* Updates the view manifestation because of a change in the data available from the feed.
* This method will be invoked for periodic refreshes as well as special requests from data.
* Invocation of this method from the MCT platform will always be in the AWT thread.
* @param data to update this view with. The map will contain a mapping from subscriptionId for
* each feed to the list (time sequenced) set of values. The will be one element in the list for each change occurring during
* the last paint cycle. There will be at least one data point per time unit.
*/
public abstract void updateFromFeed(Map<String,List<Map<String,String>>> data);
/**
* Adjust the max time request to ensure that data is not requested beyond the end of the possible time.
* @param requestSet to adjust
*/
private Map<Request,Set<FeedProvider>> adjustEndTimeForRequest(Map<Request,Set<FeedProvider>> requestSet) {
Map<Request,Set<FeedProvider>> adjustedRequest = new HashMap<Request,Set<FeedProvider>>();
for (Entry<Request,Set<FeedProvider>> entry: requestSet.entrySet()) {
// check each entry and adjust the maximum request time
for (FeedProvider fp:entry.getValue()) {
Request request = new Request(Math.min(entry.getKey().getStartTime(), fp.getValidDataExtent()),Math.min(entry.getKey().getEndTime(), fp.getValidDataExtent()));
Set<FeedProvider> providers = adjustedRequest.get(request);
if (providers == null) {
adjustedRequest.put(request, providers = new HashSet<FeedProvider>());
}
providers.add(fp);
}
}
return adjustedRequest;
}
private int getMaxSamplesSecond(Set<FeedProvider> feeds) {
int maxSamples = 0;
for (FeedProvider fp: feeds) {
maxSamples += fp.getMaximumSampleRate();
}
return maxSamples;
}
/**
* Perform a special request for data. Invoking this method is asynchronous and will return
* immediately, the transformer and renderer callback parameters are used to transform data off the AWT
* thread and to render the data. The data request may be split in multiple requests which are dispatched
* incrementally.
* @param providers to use for the data retrieval operation. If this argument is null, then the
* return value from {@link #getVisibleFeedProviders()}. No attempt is made to subscribe to ongoing events
* for feed providers.
* @param startTime to use for the request, in milliseconds since January 1, 1970
* @param endTime to use for the request, in milliseconds since January 1, 1970
* @param transformer to use during the background processing (this will not be invoked in the AWT thread).
* Null can be passed, in which case no transformation will be applied to the data.
* @param renderer to use for visualizing the data. This will be invoked in the AWT thread and must not
* be null.
* @param reverseOrder true if the data should be retrieved in reverse order, with the slice containing the end time arriving first, false otherwise.
* @throws IllegalArgumentException if renderer is null
* @return SwingWorker representing the running task, which may be canceled.
*/
public SwingWorker<Map<String, List<Map<String, String>>>, Map<String, List<Map<String, String>>>> requestData(Collection<FeedProvider> providers, long startTime, long endTime,
final DataTransformation transformer, final RenderingCallback renderer, final boolean reverseOrder) throws IllegalArgumentException {
if (renderer == null) {
throw new IllegalArgumentException("renderer cannot be null");
}
if (providers == null) {
providers = getVisibleFeedProviders();
}
assert providers != null : "visible feed providers cannot be null";
final Collection<FeedProvider> feedProviders = providers;
Map<FeedProvider, Long[]> requestTimes = new HashMap<FeedProvider, Long[]>();
for (FeedProvider provider:feedProviders) {
requestTimes.put(provider, new Long[]{!reverseOrder?startTime:endTime,!reverseOrder?endTime:startTime});
}
final Semaphore s = new Semaphore(1);
try {
s.acquire();
} catch (InterruptedException ie) {
// ignore this exception
}
FeedCycleRenderer worker = new FeedCycleRenderer(requestTimes, Collections.singleton(this)) {
@Override
protected void dispatchToFeed(FeedView manifestation,
Map<String, List<Map<String, String>>> data) {
assert manifestation == FeedView.this;
renderer.render(data);
s.release();
}
@Override
protected Collection<FeedProvider> getProviders(FeedView manifestation) {
assert manifestation == FeedView.this;
return feedProviders;
}
@Override
protected Map<Request, Set<FeedProvider>> batchByRequestTime() {
return adjustEndTimeForRequest(super.batchByRequestTime());
}
@Override
protected Map<Request, Set<FeedProvider>> getCurrentIterationRequests(
Map<Request, Set<FeedProvider>> fullSpanRequests,
Map<Request, Set<FeedProvider>> lastRequests) {
return getCurrentIterationRequestsImpl(fullSpanRequests, lastRequests, MAX_DATA_POINTS);
}
@SuppressWarnings("unchecked")
@Override
protected void requestCompleted(Map<String, List<Map<String, String>>> values, long startTime, long endTime) {
Map<String, List<Map<String, String>>> clonedValues =
new HashMap<String, List<Map<String, String>>>(values);
if (transformer != null) {
transformer.transform(clonedValues, startTime, endTime);
}
publish(clonedValues);
values.clear();
try {
while (!isCancelled() && !s.tryAcquire(300, TimeUnit.MILLISECONDS)) {
// nothing
}
} catch (InterruptedException ie) {
// this may be interrupted if the request is canceled so just return
// from this method
}
}
};
worker.execute();
return worker;
}
private Request findLastRequest(Set<FeedProvider> provider, Map<Request,Set<FeedProvider>> lastRequests) {
// simply iterate through the list to find the last request from the feed provider
Request r = null;
for (Entry<Request, Set<FeedProvider>> entry:lastRequests.entrySet()) {
if (entry.getValue() == provider) {
r = entry.getKey();
break;
}
}
return r;
}
private Map<Request, Set<FeedProvider>> getCurrentIterationRequestsImpl(
Map<Request, Set<FeedProvider>> fullSpanRequests,
Map<Request, Set<FeedProvider>> lastRequests, int maxPoints) {
Map<Request, Set<FeedProvider>> iterationRequests = new LinkedHashMap<Request, Set<FeedProvider>>();
for (Entry<Request, Set<FeedProvider>> entry: fullSpanRequests.entrySet()) {
int maxSamplesSecond = getMaxSamplesSecond(entry.getValue());
long requestInterval = entry.getKey().getEndTime() - entry.getKey().getStartTime();
double requestSpan = requestInterval/(double)1000;
double requests = Math.abs((requestSpan * maxSamplesSecond) / maxPoints);
long chunks = Math.max(1, Double.valueOf(Math.ceil(requests)).longValue());
long chunkSize = requestInterval / chunks;
Request lastRequest = findLastRequest(entry.getValue(), lastRequests);
Request fullRangeRequest = entry.getKey();
if (lastRequests.isEmpty() || (lastRequest == null)) {
// bootstrap the request, initialize the request to decrement, which is the default
long start = fullRangeRequest.getStartTime()+1;
long end = start-chunkSize;
if (requestInterval > 0) {
end = fullRangeRequest.getStartTime()-1;
start = end + chunkSize;
}
lastRequest = new Request(start,end);
}
assert lastRequest != null : "Last request should not be null.";
Request r;
if (requestInterval != 0) {
boolean startToEnd = requestInterval > 0;
if (startToEnd) {
assert chunkSize > 0;
r = new Request(lastRequest.getEndTime()+1, Math.min(lastRequest.getEndTime()+chunkSize,fullRangeRequest.getEndTime()));
if (r.getStartTime() > fullRangeRequest.getEndTime()) {
r = null;
}
} else {
assert chunkSize < 0;
r = new Request(Math.max(lastRequest.getStartTime()+chunkSize, fullRangeRequest.getEndTime()), lastRequest.getStartTime()-1);
if (r.getEndTime() < fullRangeRequest.getEndTime()) {
r = null;
}
}
} else {
r = lastRequests.isEmpty() ? fullRangeRequest:null;
}
if (r != null) {
iterationRequests.put(r, entry.getValue());
}
}
return iterationRequests;
}
/**
* This interface defines an arbitrary operation performed on set of feed data. This is intended to be used
* for both data transformation and rendering.
*/
public interface RenderingCallback {
/**
* Render the supplied feed data. The type of processing is arbitrary and based on the context
* in which the method is invoked.
* @param data to use during the operation
*/
void render(Map<String,List<Map<String,String>>> data);
}
/**
* This interface defines an arbitrary transformation on a set of feed data.
*
*/
public interface DataTransformation {
/**
* Provide a data transformation on the supplied feed data. The type of processing is arbitrary and based on the context
* in which the method is invoked.
* @param data for the parameters in the given time range
* @param startTime for the data request, this may not correspond to any times in the data set.
* @param endTime for the data request, this may not correspond to any times in the data set.
*/
void transform(Map<String, List<Map<String,String>>> data, long startTime, long endTime);
}
/**
* Update the view manifestation because of a request to synchronize all views to the
* given time. The definition of synchronization of time is specific to the view.
* @param data retrieved that was available at the syncTime
* @param syncTime to show in the view
*/
public abstract void synchronizeTime(Map<String,List<Map<String,String>>> data, long syncTime);
/**
* Gets called when time synchronization is over.
*/
protected void synchronizationDone() {
}
/**
* Show the synchronize time in a view specific manner. BETA.
* @param time to synchronize across all views, in Unix Epoch time.
* @return control or null if time cannot currently be synchronized
*/
public SynchronizationControl synchronizeTime(long time) {
return feedPool.synchronizeTime(time);
}
/**
* Provide interaction with the synchronization time state.
*
*/
public interface SynchronizationControl {
/**
* Updates the synchronization time.
* Using this method is preferable to calling {@link #synchronizationDone()} followed by {@link FeedView#synchronizeTime(long)}
* because it is atomic.
* @param time new time to synchronize on
*/
void update(long time);
/**
* Complete the time synchronization across views. This must be called in order to
* restart normal feed activity.
*/
void synchronizationDone();
}
/**
* Return feed providers current used in this manifestation. An implementation of this method
* should attempt to use visibility to only request feeds which are currently being used (instead of
* everything that could potentially be used). This method may be called from multiple threads and thus
* the implementation should ensure that iterating over the collection will not cause a concurrent modification
* exception. The easiest way to achieve this is to create the collection upon each subsequent change so the
* collection will only be write once.
* @return the feed providers currently visible in this component.
*/
public abstract Collection<FeedProvider> getVisibleFeedProviders();
/**
* A convenience method to retrieve a feed provider from a component.
* @param component to extract feed provider from
* @return FeedProvider instance or null if the component does not support feeds
*/
public FeedProvider getFeedProvider(AbstractComponent component) {
return component.getCapability(FeedProvider.class);
}
/**
* Clear the display of this manifestation that matches the provided feedProviders.
* @param feedProviders the feedProviders to be cleared.
*/
public void clear(Collection<FeedProvider> feedProviders) {
//
}
// exposed for white box testing
FeedRenderingPool getRenderingPool() {
return feedPool;
}
/**
* Get all the active feed manifestations.
* @return all the active feed manifestations.
*/
public static Set<FeedView> getAllActiveFeedManifestations() {
return feedPool.getAllActiveFeedManifestations();
}
static void resetLastDataRequestTimeToCurrentTime() {
feedPool.resetLastDataRequestTimeToCurrentTime();
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedView.java |
962 | private final AncestorListener ancestorListener = new AncestorListener() {
@Override
public void ancestorAdded(AncestorEvent event) {
feedPool.addFeedView(FeedView.this);
}
@Override
public void ancestorMoved(AncestorEvent event) {
}
@Override
public void ancestorRemoved(AncestorEvent event) {
feedPool.removeFeedView(FeedView.this);
}
}; | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedView.java |
963 | FeedCycleRenderer worker = new FeedCycleRenderer(requestTimes, Collections.singleton(this)) {
@Override
protected void dispatchToFeed(FeedView manifestation,
Map<String, List<Map<String, String>>> data) {
assert manifestation == FeedView.this;
renderer.render(data);
s.release();
}
@Override
protected Collection<FeedProvider> getProviders(FeedView manifestation) {
assert manifestation == FeedView.this;
return feedProviders;
}
@Override
protected Map<Request, Set<FeedProvider>> batchByRequestTime() {
return adjustEndTimeForRequest(super.batchByRequestTime());
}
@Override
protected Map<Request, Set<FeedProvider>> getCurrentIterationRequests(
Map<Request, Set<FeedProvider>> fullSpanRequests,
Map<Request, Set<FeedProvider>> lastRequests) {
return getCurrentIterationRequestsImpl(fullSpanRequests, lastRequests, MAX_DATA_POINTS);
}
@SuppressWarnings("unchecked")
@Override
protected void requestCompleted(Map<String, List<Map<String, String>>> values, long startTime, long endTime) {
Map<String, List<Map<String, String>>> clonedValues =
new HashMap<String, List<Map<String, String>>>(values);
if (transformer != null) {
transformer.transform(clonedValues, startTime, endTime);
}
publish(clonedValues);
values.clear();
try {
while (!isCancelled() && !s.tryAcquire(300, TimeUnit.MILLISECONDS)) {
// nothing
}
} catch (InterruptedException ie) {
// this may be interrupted if the request is canceled so just return
// from this method
}
}
}; | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedView.java |
964 | public interface DataTransformation {
/**
* Provide a data transformation on the supplied feed data. The type of processing is arbitrary and based on the context
* in which the method is invoked.
* @param data for the parameters in the given time range
* @param startTime for the data request, this may not correspond to any times in the data set.
* @param endTime for the data request, this may not correspond to any times in the data set.
*/
void transform(Map<String, List<Map<String,String>>> data, long startTime, long endTime);
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedView.java |
965 | public interface RenderingCallback {
/**
* Render the supplied feed data. The type of processing is arbitrary and based on the context
* in which the method is invoked.
* @param data to use during the operation
*/
void render(Map<String,List<Map<String,String>>> data);
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedView.java |
966 | public interface SynchronizationControl {
/**
* Updates the synchronization time.
* Using this method is preferable to calling {@link #synchronizationDone()} followed by {@link FeedView#synchronizeTime(long)}
* because it is atomic.
* @param time new time to synchronize on
*/
void update(long time);
/**
* Complete the time synchronization across views. This must be called in order to
* restart normal feed activity.
*/
void synchronizationDone();
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FeedView.java |
967 | public class FeedViewManifestationTest {
private FeedView feedManifestation;
private FeedView feedManifestation2;
private AbstractComponent component;
@Mock
private FeedProvider provider;
@Mock
private FeedProvider provider2;
@Mock
private TimeService timeService;
@Mock
private TimeService timeService2;
@Mock
private Platform platform;
@BeforeMethod
public void initialize() {
MockitoAnnotations.initMocks(this);
component = new FeedComponent();
Mockito.when(provider.getTimeService()).thenReturn(timeService);
Mockito.when(provider2.getTimeService()).thenReturn(timeService2);
feedManifestation = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String,String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return Collections.singleton(getFeedProvider(getManifestedComponent()));
}
};
feedManifestation2 = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String,String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return Collections.singleton(getFeedProvider(getManifestedComponent()));
}
};
new PlatformAccess().setPlatform(platform);
}
@AfterMethod
public void tearDown() {
new PlatformAccess().releasePlatform();
}
private static class FeedComponent extends AbstractComponent implements FeedProvider {
public FeedComponent() {
}
@Override
public String getSubscriptionId() {
return null;
}
@Override
public TimeService getTimeService() {
return null;
}
@Override
public int getMaximumSampleRate() {
return 0;
}
@Override
public boolean isPrediction() {
return false;
}
@Override
public String getCanonicalName() {
// TODO Auto-generated method stub
return null;
}
@Override
public long getValidDataExtent() {
return 0;
}
@Override
protected <T> T handleGetCapability(Class<T> capability) {
if (FeedProvider.class.isAssignableFrom(capability)) {
return capability.cast(this);
}
return null;
}
@Override
public String getLegendText() {
return null;
}
@Override
public RenderingInfo getRenderingInfo(Map<String, String> data) {
return null;
}
@Override
public FeedType getFeedType() {
return FeedType.STRING;
}
@Override
public boolean isNonCODDataBuffer() {
// TODO Auto-generated method stub
return false;
}
}
@Test
public void testPool() {
Assert.assertNotNull(feedManifestation.getRenderingPool());
}
@Test
public void testgetFeedProvider() {
Assert.assertSame(feedManifestation.getVisibleFeedProviders().iterator().next(), component);
Assert.assertSame(feedManifestation2.getVisibleFeedProviders().iterator().next(), component);
// increase coverage by invoking ancestor listeners
Assert.assertEquals(feedManifestation.getAncestorListeners().length, 1);
for (AncestorListener l : feedManifestation.getAncestorListeners()) {
l.ancestorAdded(null);
l.ancestorMoved(null);
l.ancestorRemoved(null);
}
}
@Test(expectedExceptions=IllegalArgumentException.class)
public void testRequestDataIllegalArgumentException() {
feedManifestation.requestData(null, 0, 1, null, null, true);
}
@DataProvider(name="feedRequests")
Object[][] generateFeedRequestTestData() {
return new Object[][] {
new Object[] {
1, 100, new long[] {50,Long.MAX_VALUE,50}, new long[] {50,100,50}
},
new Object[] {
7, 100, new long[] {50,25,50,2000}, new long[] {50,25,50,100}
}
};
}
@Test(dataProvider="feedRequests")
public void testAdjustEndTimeForRequest(long start, long end, long[] maxTimes, long[] expectedTimes) throws Exception {
Method m = feedManifestation.getClass().getSuperclass().getDeclaredMethod("adjustEndTimeForRequest", new Class[]{Map.class});
m.setAccessible(true);
Map<Request,Set<FeedProvider>> requestSet = new HashMap<Request,Set<FeedProvider>>();
Request r = new Request(start,end);
Set<FeedProvider> providers = new HashSet<FeedProvider>();
Map<FeedProvider,Request> expectedMaxValues = new HashMap<FeedProvider,Request>();
Set<Request> expectedRequests = new HashSet<Request>();
for (int i = 0; i < maxTimes.length; i++) {
FeedProvider fp = Mockito.mock(FeedProvider.class);
Mockito.when(fp.getValidDataExtent()).thenReturn(maxTimes[i]);
Mockito.when(fp.getMaximumSampleRate()).thenReturn(1);
Mockito.when(fp.getSubscriptionId()).thenReturn("feed"+i);
providers.add(fp);
expectedMaxValues.put(fp, new Request(start,expectedTimes[i]));
expectedRequests.add(new Request(start, expectedTimes[i]));
}
requestSet.put(r, providers);
@SuppressWarnings("unchecked")
Map<Request,Set<FeedProvider>> returnValue =
(Map<Request,Set<FeedProvider>>) m.invoke(feedManifestation, requestSet);
Assert.assertEquals(returnValue.size(), expectedRequests.size());
for (Entry<FeedProvider,Request> entry:expectedMaxValues.entrySet()) {
Assert.assertTrue(returnValue.get(entry.getValue()).contains(entry.getKey()));
}
}
@Test
public void testRequestData() throws InterruptedException {
TestDataTransform transformer = new TestDataTransform();
TestDataCallback renderer = new TestDataCallback();
final Map<String, List<Map<String, String>>> value = Collections.singletonMap("abc",
Collections.singletonList(Collections.singletonMap("time", "0")));
Mockito.when(timeService.getCurrentTime()).thenReturn(System.currentTimeMillis());
Mockito.when(provider.getSubscriptionId()).thenReturn("abc");
FeedAggregator feedAggregator = new FeedAggregator() {
@Override
public Map<String, List<Map<String, String>>> getData(Set<String> feedIDs,
TimeUnit timeUnit, long startTime, long endTime) {
return value;
}
};
Mockito.when(platform.getFeedAggregator()).thenReturn(feedAggregator);
final AtomicBoolean visibleProvidersInvoked = new AtomicBoolean(false);
feedManifestation = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String,String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
visibleProvidersInvoked.set(true);
return Collections.singleton(provider);
}
};
feedManifestation.requestData(null, 0, 1, transformer, renderer, false);
long startTime = System.currentTimeMillis();
while ((!renderer.invoked.get() || !transformer.invoked.get()) && ((System.currentTimeMillis() - startTime)<3000)) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
}
}
// verify that the callbacks were invoked
Assert.assertTrue(renderer.invoked.get());
Assert.assertTrue(transformer.invoked.get());
Assert.assertTrue(visibleProvidersInvoked.get());
visibleProvidersInvoked.set(false);
transformer = new TestDataTransform();
renderer = new TestDataCallback();
SwingWorker<Map<String, List<Map<String, String>>>, Map<String, List<Map<String, String>>>> worker =
feedManifestation.requestData(Collections.singleton(provider), 0, 1, transformer, renderer, false);
startTime = System.currentTimeMillis();
while ((!renderer.invoked.get() || !transformer.invoked.get() || !worker.isDone()) && ((System.currentTimeMillis() - startTime)<3000)) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
}
}
// verify that the callbacks were invoked
Assert.assertTrue(renderer.invoked.get());
Assert.assertTrue(transformer.invoked.get());
Assert.assertFalse(visibleProvidersInvoked.get());
}
@DataProvider(name="requestProvider")
Object[][] generateDataForCurrentIterationRequestImpl() {
FeedProvider fp = Mockito.mock(FeedProvider.class);
Mockito.when(fp.getMaximumSampleRate()).thenReturn(1);
return new Object[][] {
new Object[] {Collections.singletonMap(new Request(1000,3000), Collections.singleton(fp)), Arrays.asList(new Request(1000,1999), new Request(2000,2999), new Request(3000,3000))},
new Object[] {Collections.singletonMap(new Request(3000,1000), Collections.singleton(fp)), Arrays.asList(new Request(2001,3000), new Request(1001,2000), new Request(1000,1000))},
new Object[] {Collections.singletonMap(new Request(1000,1000), Collections.singleton(fp)), Collections.singletonList(new Request(1000,1000))}
};
}
@SuppressWarnings("unchecked")
@Test(dataProvider="requestProvider")
public void testGetCurrentIterationRequestImpl(Map<Request, Set<FeedProvider>> initialRequest, List<Request> requests) throws Exception {
feedManifestation = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String,String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return Collections.emptySet();
}
};
Method chunkMethod = FeedView.class.getDeclaredMethod("getCurrentIterationRequestsImpl", Map.class, Map.class, Integer.TYPE);
chunkMethod.setAccessible(true);
int requestNumber = 0;
Map<Request, Set<FeedProvider>> iterationRequest = (Map<Request, Set<FeedProvider>>) chunkMethod.invoke(feedManifestation, initialRequest, Collections.emptyMap(), 1);
while (!iterationRequest.isEmpty()) {
Assert.assertEquals(1, iterationRequest.size());
Entry<Request, Set<FeedProvider>> next = iterationRequest.entrySet().iterator().next();
Assert.assertEquals(next.getKey(),requests.get(requestNumber++));
iterationRequest = (Map<Request, Set<FeedProvider>>) chunkMethod.invoke(feedManifestation, initialRequest, iterationRequest, 1);
}
Assert.assertEquals(requestNumber, requests.size());
}
@Test
public void testMultipleTimeServices() throws InterruptedException, ExecutionException {
final Map<String, List<Map<String, String>>> value = Collections.singletonMap("abc",
Collections.singletonList(Collections.singletonMap("time", "1")));
final Map<String, List<Map<String, String>>> value2 = Collections.singletonMap("abc2",
Collections.singletonList(Collections.singletonMap("time", "1")));
Mockito.when(provider.getSubscriptionId()).thenReturn("abc");
Mockito.when(provider2.getSubscriptionId()).thenReturn("abc2");
FeedAggregator feedAggregator = new FeedAggregator() {
@Override
public Map<String, List<Map<String, String>>> getData(Set<String> feedIDs,
TimeUnit timeUnit, long startTime, long endTime) {
Map<String, List<Map<String, String>>> m = new HashMap<String, List<Map<String, String>>>();
m.putAll(value);
m.putAll(value2);
m.keySet().retainAll(feedIDs);
return m;
}
};
Mockito.when(platform.getFeedAggregator()).thenReturn(feedAggregator);
final Set<String> returnedFeeds = new HashSet<String>();
FeedView.RenderingCallback callback = new FeedView.RenderingCallback() {
@Override
public void render(Map<String, List<Map<String, String>>> data) {
returnedFeeds.addAll(data.keySet());
}
};
feedManifestation = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String, String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return Arrays.asList(provider, provider2);
}
};
SwingWorker<Map<String, List<Map<String, String>>>, Map<String, List<Map<String, String>>>> w = feedManifestation
.requestData(Arrays.asList(provider, provider2), 0, 10, null, callback, true);
w.get();
Assert.assertEquals(returnedFeeds, new HashSet<String>(Arrays.asList("abc", "abc2")));
}
public static class TestDataCallback implements RenderingCallback {
public Map<String, List<Map<String, String>>> data;
public AtomicBoolean invoked = new AtomicBoolean(false);
@Override
public void render(Map<String, List<Map<String, String>>> data) {
this.data = data;
invoked.set(true);
}
}
public static class TestDataTransform implements DataTransformation {
public Map<String, List<Map<String, String>>> data;
public AtomicBoolean invoked = new AtomicBoolean(false);
public long startTime;
public long endTime;
@Override
public void transform(Map<String, List<Map<String, String>>> data, long startTime, long endTime) {
this.data = data;
invoked.set(true);
this.startTime = startTime;
this.endTime = endTime;
}
}
@Test
public void testRenderingInfo() {
RenderingInfo ri = new RenderingInfo("value&value", Color.red, "", Color.orange, true);
String riAsString = ri.toString();
RenderingInfo ri2 = RenderingInfo.valueOf(riAsString);
Assert.assertEquals(ri2.getStatusColor(), Color.orange);
Assert.assertEquals(ri2.getValueText(), "value&value");
Assert.assertEquals(ri2.getValueColor(), Color.red);
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
968 | feedManifestation = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String,String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return Collections.singleton(getFeedProvider(getManifestedComponent()));
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
969 | feedManifestation2 = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String,String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return Collections.singleton(getFeedProvider(getManifestedComponent()));
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
970 | FeedAggregator feedAggregator = new FeedAggregator() {
@Override
public Map<String, List<Map<String, String>>> getData(Set<String> feedIDs,
TimeUnit timeUnit, long startTime, long endTime) {
return value;
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
971 | feedManifestation = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String,String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
visibleProvidersInvoked.set(true);
return Collections.singleton(provider);
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
972 | feedManifestation = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String,String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return Collections.emptySet();
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
973 | FeedAggregator feedAggregator = new FeedAggregator() {
@Override
public Map<String, List<Map<String, String>>> getData(Set<String> feedIDs,
TimeUnit timeUnit, long startTime, long endTime) {
Map<String, List<Map<String, String>>> m = new HashMap<String, List<Map<String, String>>>();
m.putAll(value);
m.putAll(value2);
m.keySet().retainAll(feedIDs);
return m;
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
974 | FeedView.RenderingCallback callback = new FeedView.RenderingCallback() {
@Override
public void render(Map<String, List<Map<String, String>>> data) {
returnedFeeds.addAll(data.keySet());
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
975 | feedManifestation = new FeedView(component,null) {
private static final long serialVersionUID = 1L;
@Override
public void updateFromFeed(Map<String, List<Map<String, String>>> data) {
}
@Override
public void synchronizeTime(Map<String, List<Map<String, String>>> data, long syncTime) {
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return Arrays.asList(provider, provider2);
}
}; | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
976 | private static class FeedComponent extends AbstractComponent implements FeedProvider {
public FeedComponent() {
}
@Override
public String getSubscriptionId() {
return null;
}
@Override
public TimeService getTimeService() {
return null;
}
@Override
public int getMaximumSampleRate() {
return 0;
}
@Override
public boolean isPrediction() {
return false;
}
@Override
public String getCanonicalName() {
// TODO Auto-generated method stub
return null;
}
@Override
public long getValidDataExtent() {
return 0;
}
@Override
protected <T> T handleGetCapability(Class<T> capability) {
if (FeedProvider.class.isAssignableFrom(capability)) {
return capability.cast(this);
}
return null;
}
@Override
public String getLegendText() {
return null;
}
@Override
public RenderingInfo getRenderingInfo(Map<String, String> data) {
return null;
}
@Override
public FeedType getFeedType() {
return FeedType.STRING;
}
@Override
public boolean isNonCODDataBuffer() {
// TODO Auto-generated method stub
return false;
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
977 | public static class TestDataCallback implements RenderingCallback {
public Map<String, List<Map<String, String>>> data;
public AtomicBoolean invoked = new AtomicBoolean(false);
@Override
public void render(Map<String, List<Map<String, String>>> data) {
this.data = data;
invoked.set(true);
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
978 | public static class TestDataTransform implements DataTransformation {
public Map<String, List<Map<String, String>>> data;
public AtomicBoolean invoked = new AtomicBoolean(false);
public long startTime;
public long endTime;
@Override
public void transform(Map<String, List<Map<String, String>>> data, long startTime, long endTime) {
this.data = data;
invoked.set(true);
this.startTime = startTime;
this.endTime = endTime;
}
} | false | mctcore_src_test_java_gov_nasa_arc_mct_gui_FeedViewManifestationTest.java |
979 | public class FileChooser {
// A couple flags copied from JFileChooser
/** Return value if approve (yes, ok) is chosen. */
public final static int APPROVE_OPTION = JFileChooser.APPROVE_OPTION;
/** Instruction to display only files. */
public final static int FILES_ONLY = JFileChooser.FILES_ONLY;
/** Instruction to display only files. */
public final static int FILES_AND_DIRECTORIES = JFileChooser.FILES_AND_DIRECTORIES;
@SuppressWarnings("unused")
private static final long serialVersionUID = 1L;
private String dialogTitle;
private ModalityType modalityType = ModalityType.DOCUMENT_MODAL;
private JFileChooser chooser;
private int returnValue;
private JDialog dialog;
/**
* Creates a file chooser that can be shown as a dialog.
*/
public FileChooser() {
chooser = new Chooser();
}
/**
* Pops up an "Open File" file chooser dialog. Note that the
* text that appears in the approve button is determined by
* the L&F.
*
* @param parent the parent component of the dialog,
* can be <code>null</code>;
* see <code>showDialog</code> for details
* @return the return state of the file chooser
*/
public int showOpenDialog(Component parent) {
return showDialog(parent, null);
}
/**
* Pops a custom file chooser dialog with a custom approve button.
*
* @param parent the parent component of the dialog;
* can be <code>null</code>
* @param approveButtonText the text of the <code>ApproveButton</code>
* @return the return state of the file chooser
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public int showDialog(final Component parent, final String approveButtonText) throws HeadlessException {
returnValue = JFileChooser.CANCEL_OPTION;
Frame parentFrame = (parent != null ? JOptionPane.getFrameForComponent(parent) : null);
dialog = new JDialog(parentFrame, dialogTitle, modalityType);
dialog.setLayout(new BorderLayout());
dialog.add(chooser, BorderLayout.CENTER);
dialog.pack();
dialog.setLocationRelativeTo(parentFrame);
dialog.setVisible(true);
dialog.dispose();
dialog = null;
return returnValue;
}
/**
* Sets the modality type for the file chooser dialog that will be shown.
*
* @param modalityType the new modality type
*/
public void setModalityType(ModalityType modalityType) {
this.modalityType = modalityType;
}
/**
* Sets the title of the dialog that will be shown.
*
* @param newTitle the new title
*/
public void setDialogTitle(String newTitle) {
dialogTitle = newTitle;
}
/**
* Sets the initial directory for the file chooser that will be shown.
*
* @param aDirectory to show
*/
public void setInitialDirectory(File aDirectory) {
chooser.setCurrentDirectory(aDirectory);
}
/**
* Sets the text of the approval button. Default is "open"
* for an open dialog box.
*
* @param newText the new approve button text
*/
public void setApproveButtonText(String newText) {
chooser.setApproveButtonText(newText);
}
/**
* Gets the file that was selected by the user, or null,
* if no file was selected.
*
* @return the selected file
*/
public File getSelectedFile() {
return chooser.getSelectedFile();
}
/**
* Sets the filter controlling which files we be available
* for selection.
*
* @param filter the file filter
*/
public void setFileFilter(FileFilter filter) {
chooser.setFileFilter(filter);
}
/**
* Sets the file selection mode. See {@link javax.swing.JFileChooser#setFileSelectionMode(int)}.
*
* @param mode the new file selection mode
*/
public void setFileSelectionMode(int mode) {
chooser.setFileSelectionMode(mode);
}
/**
* Sets whether multiselection is allowed.
*
* @param b true, if multiple files may be selected
*/
public void setMultiSelectionEnabled(boolean b) {
chooser.setMultiSelectionEnabled(b);
}
private void setReturnValue(int returnValue) {
this.returnValue = returnValue;
}
private void hideDialog() {
if (dialog != null) {
dialog.setVisible(false);
}
}
private class Chooser extends JFileChooser {
private static final long serialVersionUID = 1L;
@Override
public void approveSelection() {
super.approveSelection();
setReturnValue(JFileChooser.APPROVE_OPTION);
hideDialog();
}
@Override
public void cancelSelection() {
super.cancelSelection();
setReturnValue(JFileChooser.CANCEL_OPTION);
hideDialog();
}
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FileChooser.java |
980 | private class Chooser extends JFileChooser {
private static final long serialVersionUID = 1L;
@Override
public void approveSelection() {
super.approveSelection();
setReturnValue(JFileChooser.APPROVE_OPTION);
hideDialog();
}
@Override
public void cancelSelection() {
super.cancelSelection();
setReturnValue(JFileChooser.CANCEL_OPTION);
hideDialog();
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FileChooser.java |
981 | public class FrameUtil {
/**
* Returns the specified component's <code>Frame</code>.
*
* @param component the component for which we want the containing frame
* @return the frame containing the component, or null, if not contained in a frame
*/
public static Frame getFrameForComponent(Component component) {
return JOptionPane.getFrameForComponent(component);
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_FrameUtil.java |
982 | @SuppressWarnings("serial")
public abstract class GroupAction extends ContextAwareAction {
private RadioAction[] actions;
/**
* The constructor that takes a name for this action.
* @param name of type {@link String}
*/
protected GroupAction(String name) {
super(name);
}
/**
* This method returns a set of actions to be swapped for this {@link GroupAction}.
* @return an array of {@link RadioAction}
*/
public final RadioAction[] getActions() {
return actions;
}
/**
* This method sets the {@link RadioAction}s to be swapped.
* @param actions the array of {@link RadioAction}.
*/
protected final void setActions(RadioAction[] actions) {
this.actions = actions;
}
/**
* This abstract class defines the action contained in a {@link GroupAction}.
* @author [email protected]
*/
public static abstract class RadioAction extends AbstractAction {
/**
* Tests whether this radio action is in the mixed state. The mixed state is shown
* when multiple objects are selected but they have different boolean values. This
* signals to the user they values are different but selecting this action will make them
* the same.
*
* @return true if the mixed state should be shown for this radio button, false otherwise;
*/
public abstract boolean isMixed();
/**
* Tests whether or not this radio action is selected.
*
* @return true, if this radio action is selected
*/
public abstract boolean isSelected();
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_GroupAction.java |
983 | public static abstract class RadioAction extends AbstractAction {
/**
* Tests whether this radio action is in the mixed state. The mixed state is shown
* when multiple objects are selected but they have different boolean values. This
* signals to the user they values are different but selecting this action will make them
* the same.
*
* @return true if the mixed state should be shown for this radio button, false otherwise;
*/
public abstract boolean isMixed();
/**
* Tests whether or not this radio action is selected.
*
* @return true, if this radio action is selected
*/
public abstract boolean isSelected();
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_GroupAction.java |
984 | @SuppressWarnings("serial")
public class HidableTabbedPane extends JPanel {
/** The component in the first tab. We have to keep track of it here,
* because we can't insert it simultaneously into the first tab in
* the <code>JTabbedPane</code> and into the top-level panel. We'll
* remove it from one and place into the other as needed. */
private Component firstComponent;
/** The tabbed pane holding all tabs. */
private JTabbedPane tabs = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
/** A dummy component used as the first tab component when there is only one tab,
* since Java doesn't like the same object as a child of two different containers.
*/
private JPanel placeholder = new JPanel();
/**
* Create a new hideable tabbed pane with no tabs.
*/
public HidableTabbedPane() {
this.firstComponent = null;
setLayout(new BorderLayout());
instrumentNames();
}
private void instrumentNames() {
setName(UniqueNameGenerator.get("hidableTabbedPane"));
tabs.setName("tabbedPaneWithin");
}
/**
* Create a new hideable tabbed pane with the given title and component for the
* first tab (which will be hidden until we add more tabs).
*
* @param firstTabTitle the textual title of the first tab
* @param firstComponent the component to show in the first tab
*/
public HidableTabbedPane(String firstTabTitle, Component firstComponent) {
this();
this.firstComponent = firstComponent;
addTab(firstTabTitle, placeholder);
add(firstComponent, BorderLayout.CENTER);
}
/**
* Get the number of tabs in the pane.
*
* @return the number of tabs
*/
public int getTabCount() {
return tabs.getTabCount();
}
/**
* Get the index of the selected tab, 0-relative.
*
* @return the selected tab index
*/
public int getSelectedIndex() {
if (tabs.getTabCount() <= 1) {
return 0;
} else {
return tabs.getSelectedIndex();
}
}
/**
* Set the selected tab index. The index must be a valid tab index or -1, which
* indicates that no tab should be selected (can also be used when there are no
* tabs in the tabbedpane).
*
* @param index the new selected tab index
*/
public void setSelectedIndex(int index) {
tabs.setSelectedIndex(index);
}
/**
* Get the component shown in the context area of the given tab.
*
* @param index the index of the tab, 0-relative
* @return the component in the content area of the tab
*/
public Component getComponentAt(int index) {
if (index == 0) {
return firstComponent;
} else {
return tabs.getComponentAt(index);
}
}
/**
* Get the component in the tab label at the given index.
*
* @param index the tab whose tab component we want, 0-relative
* @return the component for the tab label
*/
public Component getTabComponentAt(int index) {
return tabs.getTabComponentAt(index);
}
/**
* Change the component in the content area for a tab.
*
* @param index the index of the tab to change
* @param component the new component for the content area of the tab
*/
public void setComponentAt(int index, Component component) {
if (isTabsShown()) {
tabs.setComponentAt(index, component);
}
if (index == 0) {
if (!isTabsShown()) {
if (firstComponent != null) {
remove(firstComponent);
}
if (component != null) {
add(component, BorderLayout.CENTER);
}
}
firstComponent = component;
}
validate();
}
/**
* Set the tab label component for a tab.
*
* @param index the index of the tab
* @param component the component for the tab label
*/
public void setTabComponentAt(int index, Component component) {
tabs.setTabComponentAt(index, component);
}
/**
* Check whether the tabs are shown. We show the tabs whenever the tab count
* is greater than one.
*
* @return true, if the tabs are shown
*/
public boolean isTabsShown() {
return (tabs.getTabCount() > 1);
}
/**
* Add a new tab with a textual title and content area component. Show the tabs,
* if we then have more than one tab.
*
* @param title the title for the new tab
* @param component the component for the content area
*/
public void addTab(String title, Component component) {
tabs.add(title, component);
if (tabs.getTabCount() == 2) {
showTabs();
}
}
/**
* Remove a tab. Hide the tabs, if we then have only one tab.
*
* @param index the index of the tab to remove
*/
public void removeTabAt(int index) {
tabs.removeTabAt(index);
if (tabs.getTabCount() >= 1) {
firstComponent = tabs.getComponentAt(0);
}
if (tabs.getTabCount() == 1) {
hideTabs();
}
}
/**
* Show the tabs. Move the first component into the first tab.
*/
protected void showTabs() {
if (firstComponent != null) {
remove(firstComponent);
}
tabs.setComponentAt(0, firstComponent);
add(tabs, BorderLayout.CENTER);
validate();
}
/**
* Hide the tabs. Move the first component from the first tab
* to be the entire content area.
*/
protected void hideTabs() {
remove(tabs);
tabs.setComponentAt(0, placeholder);
add(firstComponent, BorderLayout.CENTER);
validate();
}
/**
* Add a listener to notify when the currently selected tab changes.
*
* @param listener the listener
*/
public void addChangeListener(ChangeListener listener) {
tabs.addChangeListener(listener);
}
} | false | platform_src_main_java_gov_nasa_arc_mct_gui_HidableTabbedPane.java |
985 | @SuppressWarnings("serial")
public abstract class MCTFlipFlopAction extends ContextAwareAction {
private Action onStateAction;
private Action offStateAction;
private boolean state;
/**
* Creates a new toggle action with the given name and on and off
* actions.
*
* @param onStateAction the action to perform when the toggle reaches the on state
* @param offStateAction the action to perform when the toggle reaches the off state
* @param name the name of the new action
*/
protected MCTFlipFlopAction(Action onStateAction, Action offStateAction, String name) {
super(name);
this.onStateAction = onStateAction;
this.offStateAction = offStateAction;
}
/**
* Sets the state of the toggle.
*
* @param state the new state, true if the toggle is in the on state
*/
protected void setState(boolean state) {
this.state = state;
}
/**
* Gets the appropriate action to perform. The on action is
* returned if the toggle is in the on state, the off action otherwise.
*
* @return the on or off action, depending on the toggle state
*/
public Action getAction() {
return state ? onStateAction : offStateAction;
}
} | false | platform_src_main_java_gov_nasa_arc_mct_gui_MCTFlipFlopAction.java |
986 | public final class MCTGUIResourceBundle {
/** The color for the title bar on a selected view manifestation. */
public static final Color ACTIVE_COLOR = SystemColor.textHighlight;
/** The color for the title bar on an unselected view manifestation. */
public static final Color INACTIVE_COLOR = new JPanel().getBackground();
/** The width of the thick border on a selected view manifestation. */
public static final int BORDERLINE_SIZE = 5;
/** The border to use for a selected view manifestation. */
public static final Border ACTIVE_BORDER = BorderFactory.createLineBorder(MCTGUIResourceBundle.ACTIVE_COLOR, BORDERLINE_SIZE);
/** The border to use for an unselected view manifestation. */
public static final Border INACTIVE_BORDER = BorderFactory.createLineBorder(INACTIVE_COLOR, BORDERLINE_SIZE);
} | false | platform_src_main_java_gov_nasa_arc_mct_gui_MCTGUIResourceBundle.java |
987 | @SuppressWarnings("serial")
public class MCTMutableTreeNode extends DefaultMutableTreeNode {
/**
* A property name to indicate the parent of a tree node.
*/
public static final String PARENT_CLIENT_PROPERTY_NAME = "parent";
private JTree parentTree;
private boolean isProxy = false;
private boolean isVisible = true;
/**
* Creates a new tree node without attaching it to a
* parent tree.
*/
public MCTMutableTreeNode() {
super();
}
/**
* Creates a new tree node that represents the given
* user object.
*
* @param userObject a Swing component that this tree node represents
*/
public MCTMutableTreeNode(JComponent userObject) {
super(userObject);
// Add default monitored gui, which is this tree node.
if (userObject instanceof View) {
((View) userObject).addMonitoredGUI(this);
}
}
/**
* Creates a new tree node within a parent tree, that
* represents a specified user object.
*
* @param userObject a Swing component that this tree node represents
* @param parentTree the parent tree for this tree node
*/
public MCTMutableTreeNode(JComponent userObject, JTree parentTree) {
this(userObject);
this.parentTree = parentTree;
}
/**
* Creates a new tree node that represents the given
* user object. Further, the caller may specify whether
* this tree node allows children.
*
* @param userObject a Swing component that this tree node represents
* @param allowsChildren true, if the tree node should allow child nodes
*/
public MCTMutableTreeNode(JComponent userObject, boolean allowsChildren) {
this(userObject);
this.setAllowsChildren(allowsChildren);
}
/**
* Creates a new tree node within a parent tree, that
* represents a specified user object.
*
* @param userObject a Swing component that this tree node represents
* @param parentTree the parent tree for this tree node
* @param allowsChildren true, if the tree node should allow child nodes
*/
public MCTMutableTreeNode(JComponent userObject, JTree parentTree, boolean allowsChildren) {
this(userObject, parentTree);
this.setAllowsChildren(allowsChildren);
}
@Override
public void add(MutableTreeNode newChild) {
super.add(newChild);
View viewManifestation = View.class.cast(DefaultMutableTreeNode.class.cast(newChild).getUserObject());
if (viewManifestation != View.NULL_VIEW_MANIFESTATION)
viewManifestation.putClientProperty(PARENT_CLIENT_PROPERTY_NAME, getParentTree());
}
/**
* Sets whether this tree node is a proxy for another component.
*
* @param isProxy true, if this is a proxy node
*/
public void setProxy(boolean isProxy) {
this.isProxy = isProxy;
}
/**
* Tests whether this is a proxy node.
*
* @return true, if this is a proxy node
*/
public boolean isProxy() {
return this.isProxy;
}
/**
* Tests whether this tree node should be visible within the tree.
*
* @return true, if this node should be shown
*/
public boolean isVisible() {
return this.isVisible;
}
@Override
public TreeNode getChildAt(int index) {
if (children == null) {
throw new ArrayIndexOutOfBoundsException("node has no children");
}
return (TreeNode) children.get(index);
}
@Override
public int getChildCount() {
if (!isVisible) {
return 0;
}
if (children == null) {
return 0;
}
return children.size();
}
//Calls our overridden remove method
@Override
public void removeAllChildren() {
for (int i = super.getChildCount() - 1; i >= 0; i--) {
remove(i);
}
}
/**
* Remove all child nodes as well as removing registered <code>PropertyChangeListener</code>.
* @param listener the registered <code>PropertyChangeListener</code>
*/
public void removeAllChildren(PropertyChangeListener listener) {
for (int i = super.getChildCount() - 1; i >= 0; i--) {
MCTMutableTreeNode childNode = (MCTMutableTreeNode) getChildAt(i);
((View) childNode.getUserObject()).removePropertyChangeListener(listener);
remove(i);
}
}
/**
* Gets the parent tree in which this tree node is located.
*
* @return the parent tree
*/
public JTree getParentTree() {
// When a directory area is created in a new window, only the root node
// is associated with the parent tree. Here we use lazy assignment to
// to associate the parent tree to the child nodes.
if (this.parentTree == null) {
this.parentTree = ((MCTMutableTreeNode) this.getRoot()).parentTree;
}
return this.parentTree;
}
/**
* Sets the parent tree in which the tree node is located.
*
* @param parentTree the parent tree
*/
public void setParentTree(JTree parentTree) {
this.parentTree = parentTree;
}
/**
* Adds a new child of this node to the data model.
*
* @param childIndex the index at which to add the new child, or -1 to add at the end
* @param childNode the new child node
*/
private void addChild(int childIndex, MCTMutableTreeNode childNode) {
if (childIndex < 0) {
childIndex = getChildCount();
}
int oldIndex = childIndex;
// Adjust the position at which to insert the child, if it
// already existed at a position to the left of where we're
// going to insert.
if (0<=oldIndex && oldIndex<childIndex) {
--childIndex;
}
childNode.setParentTree(getParentTree());
DefaultTreeModel treeModel = (DefaultTreeModel) getParentTree().getModel();
treeModel.insertNodeInto(childNode, this, childIndex);
View viewManifestation = View.class.cast(childNode.getUserObject());
viewManifestation.putClientProperty(PARENT_CLIENT_PROPERTY_NAME, getParentTree());
}
/**
* Adds a child node and registers the <code>PropertyChangeListener</code> to
* the view of this child node.
* @param index the insert index
* @param newNode the child node to be added
* @param listener the <code>PropertyChangeListener</code>
*/
public void addChild(int index, MCTMutableTreeNode newNode, PropertyChangeListener listener) {
addChild(index, newNode);
((View) newNode.getUserObject()).addPropertyChangeListener(View.VIEW_STALE_PROPERTY, listener);
}
/**
* Refresh the tree display because of a change in a child node.
*
* @param childNode the child node that changed
*/
public void refresh(MCTMutableTreeNode childNode) {
childNode.setParentTree(getParentTree());
DefaultTreeModel treeModel = (DefaultTreeModel) parentTree.getModel();
TreePath path = getParentTree().getSelectionPath();
treeModel.insertNodeInto(childNode, this, getChildCount());
if (path != null) {
// if the parent node is in the selection path then the refresh can cause the
// selected node to be removed from the tree, so reset the selection to the
if (Arrays.asList(path).contains(this.getParent())) {
getParentTree().setSelectionPath(new TreePath(treeModel.getPathToRoot(this.getParent())));
} else {
getParentTree().setSelectionPath(path);
}
} else {
path = getPath(this);
}
getParentTree().collapsePath(path);
getParentTree().expandPath(path);
}
private TreePath getPath(MCTMutableTreeNode node) {
List<MCTMutableTreeNode> list = new LinkedList<MCTMutableTreeNode>();
// Add all nodes to list
while (node != null) {
list.add(node);
node = (MCTMutableTreeNode)node.getParent();
}
Collections.reverse(list);
// Convert array of nodes to TreePath
return new TreePath(list.toArray());
}
/**
* Refresh the tree display of this node.
*/
public void refresh() {
DefaultTreeModel treeModel = (DefaultTreeModel) parentTree.getModel();
treeModel.nodeChanged(this);
}
/**
* Remove a child node from the data model and remove the <code>PropertyChangeListener</code>
* associated to the view of the child node.
*
* @param childNode the child node to remove
* @param listener the <code>PropertyChangeListener</code>
*/
public void removeChild(MCTMutableTreeNode childNode, PropertyChangeListener listener) {
DefaultTreeModel treeModel = (DefaultTreeModel) childNode.getParentTree().getModel();
treeModel.removeNodeFromParent(childNode);
View viewManifestation = View.class.cast(childNode.getUserObject());
viewManifestation.removePropertyChangeListener(listener);
viewManifestation.putClientProperty(PARENT_CLIENT_PROPERTY_NAME, null);
}
/**
* Gets the path to this node in the parent tree.
*
* @return the path to this node
*/
public TreePath getTreePath() {
return new TreePath(getPath());
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_MCTMutableTreeNode.java |
988 | public class MCTSplitPaneFactory {
private static final String SPLIT_PANE_NAME = "splitPane";
/**
* Creates a series of {@link javax.swing.JSplitPane} objects to hold the
* given panels, in a horizontal or vertical orientation. If the number
* of panels is <em>n</em>, we create <em>n-1</em> instances of <code>JSplitPane</code>.
* The first holds the first panel and all the other <code>JSplitPane</code> instances,
* and so on recursively.
*
* @param container the container in which we will place the split panes
* @param panels the list of panels to split the container among
* @param orientation the orientation, horizontal or vertical
* @return a component that contains all the panels, organized into split panes
*/
public static JComponent createSplitPanes (Container container, List<JPanel> panels, int orientation) {
// TODO: Fix this workaround: Ran into a divide by zero condition; so, temporarily
// added return statement for new JSplitPane..
if (panels.size() == 0) {
JSplitPane splitter = new JSplitPane();
splitter.setOneTouchExpandable(true);
instrumentNames(splitter);
return splitter;
}
return createSplitPanes(container, panels, 0, panels.size() - 1, container.getWidth() / panels.size(), orientation);
}
private static JComponent createSplitPanes(Container container, List<? extends JComponent> components, int start, int end, int divide, int orientation) {
if (start == end)
return components.get(start);
else if (end - start == 1) {
JSplitPane splitPane = new JSplitPane(orientation, components.get(start), components.get(end));
splitPane.setDividerLocation(divide);
splitPane.setContinuousLayout(true);
splitPane.setOneTouchExpandable(true);
splitPane.setBorder(null);
instrumentNames(splitPane);
return splitPane;
}
else {
int middle = (start + end) / 2;
JSplitPane splitPane = new JSplitPane(orientation,
createSplitPanes(container, components, start, middle, divide, orientation),
createSplitPanes(container, components, middle + 1, end, divide, orientation));
splitPane.setDividerLocation(divide * (middle + 1));
splitPane.setContinuousLayout(true);
splitPane.setOneTouchExpandable(true);
splitPane.setBorder(null);
instrumentNames(splitPane);
return splitPane;
}
}
private static void instrumentNames(JSplitPane splitter) {
splitter.setName(UniqueNameGenerator.get(SPLIT_PANE_NAME));
}
} | false | platform_src_main_java_gov_nasa_arc_mct_gui_MCTSplitPaneFactory.java |
989 | public interface MCTViewManifestationInfo extends Serializable, NamingContext {
/** The serial version ID. */
static final long serialVersionUID = 4604437053179587058L;
/** A sentinel value indicating that a point variable has not yet been set. */
public final static Point UNDEFINED_POINT = new Point(0, 0);
// constants for the Formatting features...
/** A flag indicating the left border of a panel. */
public final static int BORDER_LEFT = 0;
/** A flag indicating the right border of a panel. */
public final static int BORDER_RIGHT = 1;
/** A flag indicating the top border of a panel. */
public final static int BORDER_TOP = 2;
/** A flag indicating the bottom border of a panel. */
public final static int BORDER_BOTTOM = 3;
/** A flag indicating that a border is a single-line border. */
public final static int BORDER_STYLE_SINGLE = 0;
/** A flag indicating that a border is a double-line border. */
public final static int BORDER_STYLE_DOUBLE = 1;
/** A flag indicating that a border is a dashed line border. */
public final static int BORDER_STYLE_DASHED = 2;
/** A flag indicating that a border is a dotted line border. */
public final static int BORDER_STYLE_DOTS = 3;
/** A flag indicating that a border is a mixed, dot-dash border. */
public final static int BORDER_STYLE_MIXED = 4;
/*
* ----- The interface methods -----
*/
/**
* Gets the dimensions of the view manifestation.
*
* @return the manifestation dimensions
*/
public Dimension getDimension();
/**
* Sets the view manifestation dimensions.
*
* @param dimension the new dimensions
*/
public void setDimension(Dimension dimension);
/**
* Gets the upper left point for the view manifestation.
*
* @return the start point
*/
public Point getStartPoint();
/**
* Sets the upper left point for the view manifestation.
*
* @param startPoint the new start point
*/
public void setStartPoint(Point startPoint);
/**
* Gets the title string to show in the title panel of the view manifestation.
*
* @return the title of the view manifestation
*/
public String getPanelTitle();
/**
* Gets the title font to show in the title panel of the view manifestation.
*
* @return the title font of the view manifestation
*/
public String getPanelTitleFont();
/**
* Gets the title font size to show in the title panel of the view manifestation.
*
* @return the title font size of the view manifestation
*/
public Integer getPanelTitleFontSize();
/**
* Gets the title font style to show in the title panel of the view manifestation.
*
* @return the title font style of the view manifestation
*/
public Integer getPanelTitleFontStyle();
/**
* Gets the title font underline style to show in the title panel of the view manifestation.
*
* @return the title font underline style of the view manifestation
*/
public Integer getPanelTitleFontUnderline();
/**
* Gets the title font color to show in the title panel of the view manifestation.
*
* @return the title font color of the view manifestation
*/
public Integer getPanelTitleFontForegroundColor();
/**
* Gets the title background color to show in the title panel of the view manifestation.
*
* @return the title background color of the view manifestation
*/
public Integer getPanelTitleFontBackgroundColor();
/**
* Sets the title string for the view manifestation.
*
* @param title the new title string
*/
public void setPanelTitle(String title);
/**
* Sets the title font for the view manifestation.
*
* @param font the new font string
*/
public void setPanelTitleFont(String font);
/**
* Sets the title font size for the view manifestation.
*
* @param fontSize the new font size
*/
public void setPanelTitleFontSize(Integer fontSize);
/**
* Sets the title font sytle for the view manifestation.
*
* @param fontStyle the new font style
*/
public void setPanelTitleFontStyle(Integer fontStyle);
/**
* Sets the title underline style for the view manifestation.
*
* @param fontStyle the new font underline style
*/
public void setPanelTitleFontUnderline(Integer fontStyle);
/**
* Sets the title font color for the view manifestation.
*
* @param color the new font color
*/
public void setPanelTitleFontForegroundColor(Integer color);
/**
* Sets the title background color for the view manifestation.
*
* @param color the new background color in sRGB
*/
public void setPanelTitleFontBackgroundColor(Integer color);
/**
* Gets the type of the view role for this view manifestation.
*
* @return the view role class
*/
public String getManifestedViewType();
/**
* Sets the view role class for this view manifestation.
*
* @param viewRoleTypeName the unique identified for this view
*/
public void setManifestedViewType(String viewRoleTypeName);
/**
* Tests whether the view manifestation has a border shown.
*
* @return true, if a border is shown
*/
public boolean hasBorder();
/**
* Tests whether the view manifestation has a border on a given
* side.
*
* @param border the border side value to test
* @return true, if the view manifestation has a border on the given side
*/
public boolean containsBorder(Integer border);
/**
* Sets whether to show a border in the view manifestation.
*
* @param showBorder true, if a border should be shown
*/
public void setHasBorder(boolean showBorder);
// formatting aspects of the panel...
/**
* Gets the border indications for the view manifestation.
*
* @return a list of border indications
*/
public List<Integer> getBorders(); // returns which borders are on/off...
/**
* Sets the border values for the view manifestation.
*
* @param borderList a list of border values for each border
*/
public void setBorders(List<Integer> borderList);
/**
* Remove a given border from the view manifestation.
* @param border the border to remove (top, right, bottom, left)
*/
public void removeBorder(Integer border);
/**
* Adds a border if it isn't already present.
*
* @param border the border to add (top, right, bottom, left)
*/
public void addBorder(Integer border);
/**
* Gets the border color to use in drawing the borders.
*
* @return the border color
*/
public Color getBorderColor();
/**
* Sets the color to use in drawing the borders.
*
* @param newColor the new border color
*/
public void setBorderColor(Color newColor);
/**
* Gets the style to use in drawing the borders.
*
* @return the border style
*/
public int getBorderStyle();
/**
* Sets the style to use in drawing the borders.
*
* @param newStyle the new border style
*/
public void setBorderStyle(int newStyle);
/**
* Tests whether the title panel is displayed.
*
* @return true, if the title panel is displayed
*/
public boolean hasTitlePanel();
/**
* Sets whether the title panel is displayed.
*
* @param hasPanel true, if the title panel should be displayed
*/
public void setHasTitlePanel(boolean hasPanel);
/**
* Gets the component id of this manifestation info.
*
* @return the component id
*/
public String getComponentId();
/**
* Sets the component id of this manifestation info.
*
* @param componentId the component id of this manifestation info
*/
public void setComponentId(String componentId);
/**
* Add a property.
*
* @param property property name
* @param value property value
*/
public void addInfoProperty(String property, String value);
/**
* Get a property value.
* @param property property name
* @return property value
*/
public String getInfoProperty(String property);
/**
* Check if the manifestation info is dirty.
* @return if the manifestation info is dirty.
*/
public boolean isDirty();
/**
* Set the dirty flag of this manifestation info.
* @param dirty dirty flag.
*/
public void setDirty(boolean dirty);
/**
* Get a named color. The ManifestationInfo is responsible for
* deciding if this comes from the UIManager or somewhere else.
* @param name the name of the color requested
* @return a color which corresponds to the name
*/
public Color getColor (String name);
/**
* Gets the nested properties that are owned by this view.
* @return the extended properties that are owned by this view
*/
public List<ExtendedProperties> getOwnedProperties();
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_MCTViewManifestationInfo.java |
990 | @XmlType(name = "ManifestInfo")
@XmlAccessorType(XmlAccessType.FIELD)
public final class MCTViewManifestationInfoImpl implements MCTViewManifestationInfo, Cloneable {
private static final long serialVersionUID = -8606703540641388677L;
private static final int DEFAULT_HEIGHT = 150;
private static final int DEFAULT_WIDTH = 250;
/** The width of the manifested view. */
protected int sizeWidth = DEFAULT_WIDTH;
/** The height of the manifested view. */
protected int sizeHeight = DEFAULT_HEIGHT;
/** The x location of the manifested view. */
protected int startPointX = UNDEFINED_POINT.x;
/** The y location of the manifested view. */
protected int startPointY = UNDEFINED_POINT.y;
/** Settings for all four borders. */
protected List<Integer> borders;
/** The border style to use. */
protected Integer borderStyle;
/** The color to use for the borders. */
protected int borderColorRGB;
/** If true, the manifested view should be shown with a title bar. */
protected boolean hasTitlePanel = true;
/** The title to show in the view title bar. */
protected String panelTitle;
/** The title font family to show in the view title bar. */
protected String panelTitleFont;
/** The title font size to show in the view title bar. */
protected Integer panelTitleFontSize;
/** The title font style to show in the view title bar. */
protected Integer panelTitleFontStyle;
/** The title font size to show in the view title bar. */
protected Integer panelTitleFontForegroundColor;
/** The title font size to show in the view title bar. */
protected Integer panelTitleFontBackgroundColor;
/** The title font text attribute to show in the view title bar. */
protected Integer panelTitleFontTextAttribute;
/** The view role type we are manifesting. */
protected String manifestedViewRoleType;
private boolean hasBorder = true;
private String componentId;
private Map<String, String> infoProperties = new HashMap<String, String>();
private List<ExtendedProperties> ownedProperties;
private transient boolean dirty = false;
/**
* For jaxb internal use only.
*/
public MCTViewManifestationInfoImpl() {
super();
}
/**
* Creates new view manifestation information for the given view role type.
*
* @param viewType
* the referenced view type
*/
public MCTViewManifestationInfoImpl(String viewType) {
this.manifestedViewRoleType = viewType;
}
@Override
public Dimension getDimension() {
return new Dimension(sizeWidth, sizeHeight);
}
@Override
public void setDimension(Dimension dimension) {
this.sizeWidth = dimension.width;
this.sizeHeight = dimension.height;
}
@Override
public void setStartPoint(Point p) {
startPointX = p.x;
startPointY = p.y;
}
@Override
public String getPanelTitle() {
return panelTitle;
}
@Override
public String getPanelTitleFont() {
return panelTitleFont;
}
@Override
public Integer getPanelTitleFontSize() {
return panelTitleFontSize;
}
@Override
public void setPanelTitleFontSize(Integer i) {
panelTitleFontSize = i;
}
@Override
public Integer getPanelTitleFontStyle() {
return panelTitleFontStyle;
}
@Override
public void setPanelTitleFontStyle(Integer i) {
panelTitleFontStyle = i;
}
@Override
public Integer getPanelTitleFontUnderline() {
return panelTitleFontTextAttribute;
}
@Override
public void setPanelTitleFontUnderline(Integer i) {
panelTitleFontTextAttribute = i;
}
@Override
public Integer getPanelTitleFontForegroundColor() {
return panelTitleFontForegroundColor;
}
@Override
public void setPanelTitleFontForegroundColor(Integer s) {
panelTitleFontForegroundColor = s;
}
@Override
public Integer getPanelTitleFontBackgroundColor() {
return panelTitleFontBackgroundColor;
}
@Override
public void setPanelTitleFontBackgroundColor(Integer s) {
panelTitleFontBackgroundColor = s;
}
@Override
public void setPanelTitle(String s) {
panelTitle = s;
}
@Override
public void setPanelTitleFont(String s) {
panelTitleFont = s;
}
@Override
public String getContextualName() {
if (!this.hasTitlePanel()) return null;
return getPanelTitle();
}
@Override
public NamingContext getParentContext() {
return null;
}
@Override
public Point getStartPoint() {
return new Point(startPointX, startPointY);
}
@Override
public String getManifestedViewType() {
return this.manifestedViewRoleType;
}
@Override
public void setManifestedViewType(String viewRoleTypeName) {
this.manifestedViewRoleType = viewRoleTypeName;
}
private transient boolean visited = false;
@Override
public Object clone() {
if (visited) {
throw new RuntimeException("cycle detected during clone");
}
MCTViewManifestationInfoImpl clonedManifestationInfo = new MCTViewManifestationInfoImpl();
try {
visited = true;
clonedManifestationInfo.componentId = this.componentId;
clonedManifestationInfo.manifestedViewRoleType = this.manifestedViewRoleType;
clonedManifestationInfo.sizeWidth = this.sizeWidth;
clonedManifestationInfo.sizeHeight = this.sizeHeight;
clonedManifestationInfo.startPointX = startPointX;
clonedManifestationInfo.startPointY = startPointY;
clonedManifestationInfo.hasBorder = this.hasBorder();
clonedManifestationInfo.borderColorRGB = this.borderColorRGB;
clonedManifestationInfo.hasTitlePanel = this.hasTitlePanel();
clonedManifestationInfo.panelTitle = this.panelTitle;
clonedManifestationInfo.panelTitleFont = this.panelTitleFont;
clonedManifestationInfo.panelTitleFontSize = this.panelTitleFontSize;
clonedManifestationInfo.panelTitleFontStyle = this.panelTitleFontStyle;
clonedManifestationInfo.panelTitleFontTextAttribute = this.panelTitleFontTextAttribute;
clonedManifestationInfo.panelTitleFontForegroundColor = this.panelTitleFontForegroundColor;
clonedManifestationInfo.panelTitleFontBackgroundColor = this.panelTitleFontBackgroundColor;
clonedManifestationInfo.infoProperties.putAll(this.infoProperties);
clonedManifestationInfo.ownedProperties = ownedProperties == null ? null : new ArrayList<ExtendedProperties>(ownedProperties.size());
if (ownedProperties != null) {
for (ExtendedProperties ep:ownedProperties) {
clonedManifestationInfo.ownedProperties.add(ep.clone());
}
}
} finally {
visited = false;
}
return clonedManifestationInfo;
}
@Override
public boolean hasBorder() {
return hasBorder;
}
@Override
public void setHasBorder(boolean setting) {
this.hasBorder = setting;
}
@Override
public boolean hasTitlePanel() {
return hasTitlePanel;
}
@Override
public void setHasTitlePanel(boolean setting) {
hasTitlePanel = setting;
}
@Override
public List<Integer> getBorders() {
if (borders == null) { // not initialized yet...
borders = new ArrayList<Integer>();
borders.add(BORDER_LEFT);
borders.add(BORDER_RIGHT);
borders.add(BORDER_TOP);
borders.add(BORDER_BOTTOM);
}
return borders;
}
@Override
public void setBorders(List<Integer> borderList) {
this.borders = borderList;
}
@Override
public boolean containsBorder(Integer border) {
if (borders == null) {
return false;
}
Iterator<Integer> iter = borders.iterator();
while (iter.hasNext()) {
Integer aBorder = iter.next();
if (border.intValue() == aBorder.intValue()) {
return true;
}
}
return false;
}
@Override
public void removeBorder(Integer border) {
if (borders != null) {
while (borders.contains(border)) {
borders.remove(border);
}
}
}
@Override
public void addBorder(Integer border) {
if (borders == null)
borders = new ArrayList<Integer>();
if (!containsBorder(border))
borders.add(border);
setBorders(this.borders);
}
@Override
public Color getBorderColor() {
return new Color(borderColorRGB);
}
@Override
public void setBorderColor(Color newColor) {
this.borderColorRGB = newColor.getRGB();
}
@Override
public int getBorderStyle() {
if (borderStyle == null)
borderStyle = BORDER_STYLE_SINGLE;
return borderStyle;
}
@Override
public void setBorderStyle(int newStyle) {
this.borderStyle = newStyle;
}
@Override
public String getComponentId() {
return componentId;
}
@Override
public void setComponentId(String componentId) {
this.componentId = componentId;
}
@Override
public void addInfoProperty(String property, String value) {
this.infoProperties.put(property, value);
}
@Override
public String getInfoProperty(String property) {
return infoProperties.get(property);
}
@Override
public boolean isDirty() {
return dirty;
}
@Override
public void setDirty(boolean dirty) {
this.dirty = dirty;
}
@Override
public Color getColor(String name) {
return UIManager.getColor(name);
}
@Override
public List<ExtendedProperties> getOwnedProperties() {
if (ownedProperties == null) {
ownedProperties = new ArrayList<ExtendedProperties>();
}
return ownedProperties;
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_MCTViewManifestationInfoImpl.java |
991 | public final class MenuExtensionManager implements MenuManager {
private static final MCTLogger LOGGER = MCTLogger.getLogger(MenuExtensionManager.class);
private static final MenuExtensionManager manager = new MenuExtensionManager();
private final Map<String, List<MenuItemInfo>> map = new HashMap<String, List<MenuItemInfo>>();
/** A private constructor, to enforce the singleton pattern. */
private MenuExtensionManager() {
}
/**
* Gets the singleton instance of the menu extension manager.
*
* @return the menu extension manager instance
*/
public static MenuExtensionManager getInstance() {
return manager;
}
/**
* Refreshes all extended menus by unregistering all extended
* menu actions and then reregistering all those actions from
* the given providers.
*
* @param providers the set of providers of extended menu actions
*/
public synchronized void refreshExtendedMenus(List<ExtendedComponentProvider> providers) {
// Clean up existing extended actions.
for (Entry<String, List<MenuItemInfo>> entry : map.entrySet()) {
List<MenuItemInfo> infos = entry.getValue();
for (MenuItemInfo info : infos) {
if (info.getType() == MenuItemType.SUBMENU)
ActionManager.unregisterMenu(info.getMenuClass(), info.getCommandKey());
else
ActionManager.unregisterAction(info.getActionClass(), info.getCommandKey());
}
}
map.clear();
// Add new extended actions.
for (ExtendedComponentProvider provider : providers) {
try {
if (provider.getMenuItemInfos() != null) {
for (MenuItemInfo info : provider.getMenuItemInfos()) {
registerExtendedMenu(info);
}
}
} catch (Exception e) {
// if an exception occurs, log an error for the provider to resolve but
// continue through the rest of the providers
LOGGER.error("Error occurred while invoking provider: " + provider.getClass().getName() +
" from bundle: " + provider.getBundleSymbolicName(), e);
}
}
}
/**
* Registers a new extended menu item.
*
* @param info the information describing the new menu item and the associated action
*/
public void registerExtendedMenu(MenuItemInfo info) {
if (info.getType() == MenuItemType.SUBMENU) {
ActionManager.registerMenu(info.getMenuClass(), info.getCommandKey());
} else {
ActionManager.registerAction(info.getActionClass(), info.getCommandKey());
}
String menubarPath = info.getMenubarPath();
List<MenuItemInfo> extendedMenus = map.get(menubarPath);
if (extendedMenus == null) {
extendedMenus = new ArrayList<MenuItemInfo>();
}
extendedMenus.add(info);
map.put(menubarPath, extendedMenus);
}
/**
* Gets a list of extended menu items for the given menu path.
*
* @param menubarPath the path describing the menu path to the items
* @return the list of extended menu items at that path
*/
public List<MenuItemInfo> getExtendedMenus(String menubarPath) {
List<MenuItemInfo> list = map.get(menubarPath);
return list == null ? Collections.<MenuItemInfo>emptyList() : Collections.unmodifiableList(list);
}
/**
* Returns the <code>JPopupMenu</code> for this <code>MCTViewManifestation</code>.
* @param manifestation the manifestation
* @return the popup menu
*/
public JPopupMenu getManifestationPopupMenu(View manifestation) {
ActionContextImpl context = new ActionContextImpl();
Container housing = SwingUtilities.getAncestorOfClass(MCTHousing.class, manifestation);
assert housing instanceof MCTHousing : "All manifestations should be contained in an MCTHousing.";
context.setTargetHousing((MCTHousing) housing);
Collection<View> selectedManifestations =
context.getTargetHousing().getSelectionProvider().getSelectedManifestations();
for (View selectedManifestation: selectedManifestations) {
context.addTargetViewComponent(selectedManifestation);
}
return MenuFactory.createUserObjectPopupMenu(context);
}
/**
* Returns the <code>JPopupMenu</code> applicable for this manifestation when
* viewed in the center pane.
* @param manifestation the manifestation in the center pane
* @return the popup menu
*/
@Override
public JPopupMenu getViewPopupMenu(View manifestation) {
ActionContextImpl context = new ActionContextImpl();
context.setTargetComponent(manifestation.getManifestedComponent());
context.setTargetHousing((MCTHousing) SwingUtilities.getAncestorOfClass(MCTAbstractHousing.class, manifestation));
return MenuFactory.createViewPopupMenu(context);
}
} | false | platform_src_main_java_gov_nasa_arc_mct_gui_MenuExtensionManager.java |
992 | public final class MenuItemInfo {
/**
* MCT-supported menu item types.
*/
public enum MenuItemType {
/** Renders the item as a <code>JMenuItem</code>. */
NORMAL,
/** Renders the item as a <code>JMenu</code>. */
SUBMENU,
/** Renders the item as a <code>JCheckBoxMenuItem</code>. */
CHECKBOX,
/** Renders the item as a set of <code>JRadioButtonMenuItems</code>. */
RADIO_GROUP,
/** Renders the item as a set of <code>JMenuItems</code>. */
COMPOSITE;
}
private String menubarPath;
private String commandKey;
private MenuItemType type;
private Class<? extends ContextAwareAction> actionClass;
private Class<? extends ContextAwareMenu> menuClass;
/**
* Create menu item information for the given command key and {@link MenuItemType}.
* <p>
* This constructor is used when:
* <ul>
* <li> a menubar path is later provided in {@link ContextAwareMenu#addMenuItemInfos(String, java.util.Collection)}
* <li>the actual {@link Class} instance of the {@link ContextAwareAction} is later associated.
* </ul>
* <p>
* <b>Warning:</b> this method is only internally used.
* @param commandKey the action command key
* @param type the type of the menu item
*/
public MenuItemInfo(String commandKey, MenuItemType type) {
this.commandKey = commandKey;
this.type = type;
}
/**
* The constructor that takes a menubar path, command key, {@link MenuItemType},
* and the {@link Class} of a {@link ContextAwareAction}.
* @param menubarPath the menubar path of type {@link String}
* @param commandKey the command key of type {@link String}
* @param type the menu item type of type {@link MenuItemType}
* @param actionClass the class instance of a {@link ContextAwareAction}
*/
public MenuItemInfo(String menubarPath, String commandKey, MenuItemType type, Class<? extends ContextAwareAction> actionClass) {
this(commandKey, type);
this.menubarPath = menubarPath;
this.actionClass = actionClass;
}
/**
* The constructor that takes a menubar path, command key,
* and the {@link Class} of a {@link ContextAwareMenu}.
* @param menubarPath the menubar path of type {@link String}
* @param commandKey the command key of type {@link String}
* @param menuClass the class instance of a {@link ContextAwareMenu}
*/
public MenuItemInfo(String menubarPath, String commandKey, Class<? extends ContextAwareMenu> menuClass) {
this(commandKey, MenuItemType.SUBMENU);
this.menubarPath = menubarPath;
this.menuClass = menuClass;
}
/**
* This method returns the menubar path of this {@link MenuItemInfo}.
* @return the menubar path of type {@link String}
*/
public String getMenubarPath() {
return menubarPath;
}
/**
* This method returns the command associated with this {@link MenuItemInfo}.
* @return the command key of type {@link String}
*/
public String getCommandKey() {
return commandKey;
}
/**
* This method returns the type of this {@link MenuItemInfo}.
* @return the menu item type of type {@link MenuItemType}
*/
public MenuItemType getType() {
return type;
}
/**
* This method returns the associated {@link Class} instance of a
* {@link ContextAwareAction}.
* @return a {@link Class} instance of the associated {@link ContextAwareAction}
*/
public Class<? extends ContextAwareAction> getActionClass() {
return actionClass;
}
/**
* This method returns the associated {@link Class} instance of a
* {@link ContextAwareMenu}.
* @return a {@link Class} instance of the associated {@link ContextAwareMenu}
*/
public Class<? extends ContextAwareMenu> getMenuClass() {
return menuClass;
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_MenuItemInfo.java |
993 | public enum MenuItemType {
/** Renders the item as a <code>JMenuItem</code>. */
NORMAL,
/** Renders the item as a <code>JMenu</code>. */
SUBMENU,
/** Renders the item as a <code>JCheckBoxMenuItem</code>. */
CHECKBOX,
/** Renders the item as a set of <code>JRadioButtonMenuItems</code>. */
RADIO_GROUP,
/** Renders the item as a set of <code>JMenuItems</code>. */
COMPOSITE;
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_MenuItemInfo.java |
994 | public final class MenuSection {
private String menubarPath;
private List<MenuItemInfo> list;
/**
* Constructor.
* @param menubarPath the menubarPath
*/
public MenuSection(String menubarPath) {
this.menubarPath = menubarPath;
}
/**
* @return the menubarPath
*/
public String getMenubarPath() {
return menubarPath;
}
/**
* Adds a MenuItemInfo to this section.
* @param info MenuItemInfo
*/
public void addMenuItemInfo(MenuItemInfo info) {
if (list == null)
list = new ArrayList<MenuItemInfo>();
boolean found = false;
for (MenuItemInfo menuItemInfo : list) {
String commandKey = info.getCommandKey();
if (menuItemInfo.getCommandKey().equals(commandKey)) {
found = true;
break;
}
}
if (!found)
list.add(info);
}
/**
* @return the list of MenuItemInfo contained in this section
*/
public List<MenuItemInfo> getMenuItemInfoList() {
return list == null ? Collections.<MenuItemInfo>emptyList() : Collections.unmodifiableList(list);
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_MenuSection.java |
995 | public interface NamingContext {
/**
* Returns the parent context to used for labeling.
* @return NamingContext that represents the parent of this context or null if there is no viable parent.
*/
public NamingContext getParentContext();
/**
* Returns a string representing the name used by this labeling context.
* @return name that is currently used by this context.
*/
public String getContextualName();
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_NamingContext.java |
996 | public class OptionBox {
// Values copied from JOptionPane, so that code which uses this class doesn't
// also need to import JOptionPane.
/** No icon is used. */
public static final int PLAIN_MESAGE = JOptionPane.PLAIN_MESSAGE;
/** Used for error messages. */
public static final int ERROR_MESSAGE = JOptionPane.ERROR_MESSAGE;
/** Used for warning messages. */
public static final int WARNING_MESSAGE = JOptionPane.WARNING_MESSAGE;
/** Used for questions. */
public static final int QUESTION_MESSAGE = JOptionPane.QUESTION_MESSAGE;
/** Used for Information messages. */
public static final int INFORMATION_MESSAGE = JOptionPane.INFORMATION_MESSAGE;
/** Type used for <code>showConfirmDialog</code>. */
public static final int OK_CANCEL_OPTION = JOptionPane.OK_CANCEL_OPTION;
/** Return value from class method if YES is chosen. */
public static final int YES_OPTION = JOptionPane.YES_OPTION;
/** Type used for <code>showConfirmDialog</code>. */
public static final int YES_NO_OPTION = JOptionPane.YES_NO_OPTION;
/** Type used for <code>showConfirmDialog</code>. */
public static final int YES_NO_CANCEL_OPTION = JOptionPane.YES_NO_CANCEL_OPTION;
/** Return value from class method if user closes window without selecting anything,
* more than likely this should be treated as either a <code>CANCEL_OPTION</code>
* or <code>NO_OPTION</code>. */
public static final int CLOSED_OPTION = JOptionPane.CLOSED_OPTION;
/** Return value from class method if NO is chosen. */
public static final int NO_OPTION = JOptionPane.NO_OPTION;
/** Return value from class method if OK is chosen. */
public static final int OK_OPTION = JOptionPane.OK_OPTION;
/** Return value from class method if Cancel is chosen. */
public static final int CANCEL_OPTION = JOptionPane.CANCEL_OPTION;
/** Type meaning Look and Feel should not supply any options --
* only use the options from the <code>JOptionPane</code>.
*/
public static final int DEFAULT_OPTION = JOptionPane.DEFAULT_OPTION;
/**
* Brings up an information-message dialog titled "Message".
*
* @param parentComponent determines the <code>Frame</code> in
* which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static void showMessageDialog(Component parentComponent,
Object message) throws HeadlessException {
showMessageDialog(parentComponent, message, "Message",
JOptionPane.INFORMATION_MESSAGE);
}
/**
* Brings up a dialog that displays a message using a default
* icon determined by the <code>messageType</code> parameter.
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static void showMessageDialog(Component parentComponent,
Object message, String title, int messageType)
throws HeadlessException {
showMessageDialog(parentComponent, message, title, messageType, null);
}
/**
* Brings up a dialog displaying a message, specifying all parameters.
*
* @param parentComponent determines the <code>Frame</code> in which the
* dialog is displayed; if <code>null</code>,
* or if the <code>parentComponent</code> has no
* <code>Frame</code>, a
* default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param messageType the type of message to be displayed:
* <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param icon an icon to display in the dialog that helps the user
* identify the kind of message that is being displayed
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
private static void showMessageDialog(Component parentComponent,
Object message, String title, int messageType, Icon icon)
throws HeadlessException {
showOptionDialog(parentComponent, message, title, JOptionPane.DEFAULT_OPTION,
messageType, icon, null, null);
}
/**
* Brings up a dialog with a specified icon, where the initial
* choice is determined by the <code>initialValue</code> parameter and
* the number of choices is determined by the <code>optionType</code>
* parameter.
* <p>
* If <code>optionType</code> is <code>YES_NO_OPTION</code>,
* or <code>YES_NO_CANCEL_OPTION</code>
* and the <code>options</code> parameter is <code>null</code>,
* then the options are
* supplied by the look and feel.
* <p>
* The <code>messageType</code> parameter is primarily used to supply
* a default icon from the look and feel.
*
* @param parentComponent determines the <code>Frame</code>
* in which the dialog is displayed; if
* <code>null</code>, or if the
* <code>parentComponent</code> has no
* <code>Frame</code>, a
* default <code>Frame</code> is used
* @param message the <code>Object</code> to display
* @param title the title string for the dialog
* @param optionType an integer designating the options available on the
* dialog: <code>DEFAULT_OPTION</code>,
* <code>YES_NO_OPTION</code>,
* <code>YES_NO_CANCEL_OPTION</code>,
* or <code>OK_CANCEL_OPTION</code>
* @param messageType an integer designating the kind of message this is,
* primarily used to determine the icon from the
* pluggable Look and Feel: <code>ERROR_MESSAGE</code>,
* <code>INFORMATION_MESSAGE</code>,
* <code>WARNING_MESSAGE</code>,
* <code>QUESTION_MESSAGE</code>,
* or <code>PLAIN_MESSAGE</code>
* @param icon the icon to display in the dialog
* @param options an array of objects indicating the possible choices
* the user can make; if the objects are components, they
* are rendered properly; non-<code>String</code>
* objects are
* rendered using their <code>toString</code> methods;
* if this parameter is <code>null</code>,
* the options are determined by the Look and Feel
* @param initialValue the object that represents the default selection
* for the dialog; only meaningful if <code>options</code>
* is used; can be <code>null</code>
* @return an integer indicating the option chosen by the user,
* or <code>CLOSED_OPTION</code> if the user closed
* the dialog
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public static int showOptionDialog(Component parentComponent,
Object message, String title, int optionType, int messageType,
Icon icon, Object[] options, Object initialValue)
throws HeadlessException {
JOptionPane pane = new JOptionPane(message, messageType,
optionType, icon,
options, initialValue
);
pane.setInitialValue(initialValue);
pane.setComponentOrientation(((parentComponent == null) ?
JOptionPane.getRootFrame() : parentComponent).getComponentOrientation());
pane.setMessageType(messageType);
JDialog dialog = pane.createDialog(parentComponent, title);
pane.selectInitialValue();
// These two lines are different from JOptionPane.showOptionDialog().
dialog.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
dialog.setLocationRelativeTo(parentComponent);
dialog.setVisible(true);
dialog.dispose();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return JOptionPane.CLOSED_OPTION;
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue).intValue();
return JOptionPane.CLOSED_OPTION;
}
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return JOptionPane.CLOSED_OPTION;
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_OptionBox.java |
997 | public class Request {
private final long startTime;
private final long endTime;
/**
* Creates a new instance of a request.
* @param start time of the request, in Unix epoch time.
* @param end time of the request in Unix epoch time.
*/
public Request(long start, long end) {
startTime = start;
endTime = end;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Request && ((Request) obj).endTime == endTime
&& ((Request) obj).startTime == startTime;
}
@Override
public int hashCode() {
return (int) ((startTime + endTime) % Integer.MAX_VALUE);
}
/**
* Gets the start time.
* @return start time of the request.
*/
public long getStartTime() {
return startTime;
}
/**
* Gets the end time.
* @return end time of the request.
*/
public long getEndTime() {
return endTime;
}
@Override
public String toString() {
return "Request["+getStartTime()+","+getEndTime()+"]";
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_Request.java |
998 | @SuppressWarnings("serial")
public class RowSize implements Serializable {
/*
* Row key
*/
private Object rowKey;
/**
* Gets the key for the row we are storing the row size for.
* The row key is used by the caller to remember the row for
* which we hold the size. The key is not interpreted by
* this class.
*
* @return the row key
*/
public Object getRowKey() {
return rowKey;
}
/**
* Sets the key for the row we are storing the row size for.
*
* @param rowKey the key to the row
*/
public void setRowKey(Object rowKey) {
this.rowKey = rowKey;
}
/*
* Row height
*/
private Integer height;
/**
* Gets the height of the row we are holding
* the height for.
*
* @return the row height
*/
public Integer getHeight() {
return height;
}
/**
* Sets the row height to a new value.
*
* @param height the new row height
*/
public void setHeight(Integer height) {
this.height = height;
}
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_RowSize.java |
999 | public interface SelectionProvider {
/**
* Defines the property name when the set of selected manifestations changes.
*/
public static String SELECTION_CHANGED_PROP = "selectionChanged";
/**
* Adds a listener to receive events when the set of selected manifestations
* changes. The property name will be {@link SelectionProvider#SELECTION_CHANGED_PROP}.
* @param listener to receive events when the selection is changed
*/
void addSelectionChangeListener(PropertyChangeListener listener);
/**
* Removes listener.
* @param listener to remove.
*/
void removeSelectionChangeListener(PropertyChangeListener listener);
/**
* Returns the selected manifestations.
* @return currently selected manifestations, the result may be empty but not null
*/
Collection<View> getSelectedManifestations();
/**
* Clears the set of current selections such that calling {@link #getSelectedManifestations()} will return
* an empty collection <code>getSelectedManifestations().isEmpty() == true</code>. Selection events must not be fired during
* the invocation of this method.
*/
void clearCurrentSelections();
} | false | mctcore_src_main_java_gov_nasa_arc_mct_gui_SelectionProvider.java |