Unnamed: 0
int64
0
2.05k
func
stringlengths
27
124k
target
bool
2 classes
project
stringlengths
39
117
1,800
private static final class Reference<E> { private E referent; Reference(E element) { this.referent = element; } void clear() { this.referent = null; } E get() { return this.referent; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_util_LinkedHashSet.java
1,801
private final class SetIterator implements Iterator<E> { private Iterator<Reference<E>> parentIterator; private E nextElement; public SetIterator(Iterator<Reference<E>> parentIterator) { this.parentIterator = parentIterator; } @Override public boolean hasNext() { if (nextElement != null) { return true; } boolean hasNext = false; while (!hasNext) { if (!parentIterator.hasNext()) { break; } Reference<E> nextRef = parentIterator.next(); nextElement = nextRef.get(); if (nextElement != null) { hasNext = true; } else { remove(); } } return hasNext; } @Override public E next() { if (nextElement != null) { E returnValue = nextElement; nextElement = null; return returnValue; } else if (hasNext()) { E returnValue = nextElement; nextElement = null; return returnValue; } else { throw new NoSuchElementException(); } } @Override public void remove() { synchronized (LinkedHashSet.this) { parentIterator.remove(); } } }
false
mctcore_src_main_java_gov_nasa_arc_mct_util_LinkedHashSet.java
1,802
public class LinkedHashSetTest { private LinkedHashSet<String> strSet; @BeforeMethod public void setup() { strSet = new LinkedHashSet<String>(); } @Test() public void addTest() { String[] data = getStringTestData(); for (String str: data) { strSet.add(str); } int index = data.length-1; for (String str: strSet) { Assert.assertEquals(str, data[index--]); } } @Test() public void offerLastTest() { String[] data = getStringTestData(); for (String str: data) { strSet.offerLast(str); } int index = 0; for (String str: strSet) { Assert.assertEquals(str, data[index++]); } } @Test() public void removeTest() { String[] data = getStringTestData(); for (String str: data) { strSet.offerLast(str); } Assert.assertEquals(strSet.size(), 3); strSet.remove(data[1]); Assert.assertEquals(strSet.size(), 2); Iterator<String> it = strSet.iterator(); Assert.assertTrue(it.hasNext()); String str = it.next(); Assert.assertEquals(str, data[0]); Assert.assertTrue(it.hasNext()); str = it.next(); Assert.assertEquals(str, data[2]); Assert.assertFalse(it.hasNext()); } public String[] getStringTestData() { return new String[] { "str1", "str2", "str3" }; } }
false
mctcore_src_test_java_gov_nasa_arc_mct_util_LinkedHashSetTest.java
1,803
public enum LookAndFeelSettings { /** L&F settings instance. */ INSTANCE; private static final MCTLogger logger = MCTLogger.getLogger(LookAndFeelSettings.class); private static UIDefaults lafDefaults = UIManager.getLookAndFeelDefaults(); private static Color WINDOW; private static Color WINDOW_BORDER; private static Color MENUBAR_BACKGROUND; private static Color TREE_SELECTION_BACKGROUND; private static Color TEXT_HIGHLIGHT; private static ColorScheme BASE_PROPERTIES = new ColorScheme(); /** The viewColor string constant. */ public final static String viewColor = "viewColor"; /** * As a convenience, allow config file to specify "Metal" or Nimbus". Absence of the * parameter results in default to Metal. Otherwise, the config file must provide a * fully qualified LAF name. * @param lookAndFeelStr - L&F string. */ public void setLAF(String lookAndFeelStr) { String exceptionNotice = ""; try { // Set the font for Metal LAF to non-bold, in case Metal is used UIManager.put("swing.boldMetal", Boolean.FALSE); if (lookAndFeelStr == null || lookAndFeelStr.equalsIgnoreCase("Metal")) { UIManager.setLookAndFeel(new MetalLookAndFeel()); } else if (lookAndFeelStr.equalsIgnoreCase("Nimbus")) { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if (info.getName().equals("Nimbus")) { UIManager.setLookAndFeel(info.getClassName()); break; } } } else { UIManager.setLookAndFeel(lookAndFeelStr); } } catch (UnsupportedLookAndFeelException e) { exceptionNotice = "UnsupportedLookAndFeelException"; } catch (ClassNotFoundException e) { exceptionNotice = "ClassNotFoundException"; } catch (InstantiationException e) { exceptionNotice = "InstantiationException"; } catch (IllegalAccessException e) { exceptionNotice = "IllegalAccessException"; } finally { if (! exceptionNotice.isEmpty()) { try { // The desired LAF was not created, so try to use the Metal LAF as a default. UIManager.setLookAndFeel(new MetalLookAndFeel()); } catch (UnsupportedLookAndFeelException e) { logger.error("Could not initialize the Swing Look and Feel settings, MCT is closing."); System.exit(1); } } } // Look and Feel has been successfully created, now set colors initializeColors(UIManager.getLookAndFeel()); Properties props = new Properties(); String filename = System.getProperty(viewColor,"resources/properties/viewColor.properties"); FileReader reader = null; try { reader = new FileReader(filename); props.load(reader); BASE_PROPERTIES = new ColorScheme(props); BASE_PROPERTIES.applyColorScheme(); // Apply top-level color bindings } catch (Exception e) { logger.warn("Using default color and font properties because could not open viewColor properties file :"+filename); BASE_PROPERTIES = new ColorScheme(); } finally { try { if (reader != null) reader.close(); } catch(IOException ioe1){ } } } private void initializeColors(LookAndFeel lookAndFeel) { lafDefaults = UIManager.getLookAndFeelDefaults(); if (lookAndFeel instanceof MetalLookAndFeel) { WINDOW = lafDefaults.getColor("window"); WINDOW_BORDER = lafDefaults.getColor("windowBorder"); } else if (lookAndFeel instanceof NimbusLookAndFeel) { WINDOW = lafDefaults.getColor("Panel.background"); WINDOW_BORDER = lafDefaults.getColor("nimbusBorder"); } else { logger.error("Look and Feel reference is invalid: " + lookAndFeel.getName() + ". MCT is closing."); System.exit(1); } MENUBAR_BACKGROUND = lafDefaults.getColor("MenuBar.background"); TREE_SELECTION_BACKGROUND = lafDefaults.getColor("Tree.selectionBackground"); TEXT_HIGHLIGHT = lafDefaults.getColor("textHighlight"); LafColor.refresh(); } /** * Checks for whether it's been initialized or not. * @return boolean - flag to check for initialization. */ public boolean isInitialized() { return (WINDOW != null && WINDOW_BORDER != null); } /** * Gets the window color. * @return Color - window color. */ public static Color getWindowColor() { return WINDOW; } /** * Window border color. * @return Color - window border color. */ public static Color getWindowBorderColor() { return WINDOW_BORDER; } /** * Gets the menubar background color. * @return Color - Menubar background color. */ public static Color getMenubarColor() { return MENUBAR_BACKGROUND; } /** * Gets the tree selection background color. * @return Color - Tree selection background color. */ public static Color getTreeSelectionColor() { return TREE_SELECTION_BACKGROUND; } /** * Gets the text hightlight color. * @return Color - Text highlight color. */ public static Color getTextHighlightColor() { return TEXT_HIGHLIGHT; } /** * Gets the base color properties. * @return Color - Base properties color. */ public static ColorScheme getColorProperties() { return BASE_PROPERTIES; } }
false
util_src_main_java_gov_nasa_arc_mct_util_LookAndFeelSettings.java
1,804
public class MCTIcons { private static ImageIcon warningIcon32x32 = new ImageIcon(ClassLoader.getSystemResource("images/warning_32x32.png")); private static ImageIcon errorIcon32x32 = new ImageIcon(ClassLoader.getSystemResource("images/error_32x32.png")); private static ImageIcon componentIcon12x12 = new ImageIcon(ClassLoader.getSystemResource("images/object_icon.png")); private static enum Icons { WARNING_ICON, ERROR_ICON, COMPONENT_ICON }; private static ImageIcon getIcon(Icons anIconEnum) { switch(anIconEnum) { case WARNING_ICON: return warningIcon32x32; case ERROR_ICON: return errorIcon32x32; case COMPONENT_ICON: return componentIcon12x12; default: return null; } } /** * Gets the warning image icon. * @return ImageIcon - the image icon. */ public static ImageIcon getWarningIcon() { return getIcon(Icons.WARNING_ICON); } /** * Gets the error image icon scaled to designated width and height. * @param width - number. * @param height - number. * @return the error image icon. */ public static ImageIcon getErrorIcon(int width, int height) { Image scaled = getIcon(Icons.ERROR_ICON).getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH); return new ImageIcon(scaled); } /** * Gets the component image icon. * @return the component image icon. */ public static ImageIcon getComponent() { return getIcon(Icons.COMPONENT_ICON); } private MCTIcons() { // no instantiation } }
false
util_src_main_java_gov_nasa_arc_mct_util_MCTIcons.java
1,805
private static enum Icons { WARNING_ICON, ERROR_ICON, COMPONENT_ICON };
false
util_src_main_java_gov_nasa_arc_mct_util_MCTIcons.java
1,806
public class MCTIconsTest { @Test public void testIcons() throws Exception { ImageIcon icon; icon = MCTIcons.getWarningIcon(); assertNotNull(icon); icon = MCTIcons.getErrorIcon(100, 50); assertNotNull(icon); icon = MCTIcons.getComponent(); assertNotNull(icon); } }
false
util_src_test_java_gov_nasa_arc_mct_util_MCTIconsTest.java
1,807
public class ParameterInfo { private String symbolName; private String displayName; /** * Specifies a component. * @param id the unique symbol name * @param name human readable string describing the component type * @throws Exception if error */ public ParameterInfo(String id, String name) throws Exception { if (id == null || id.isEmpty()) { throw new Exception("symbol id must be non empty."); } if (name == null) { throw new Exception("display name must be non null."); } this.symbolName = id; this.displayName = name; } @Override public final boolean equals(Object obj) { return obj instanceof ParameterInfo && ((ParameterInfo)obj).getSymbolName().equals(getSymbolName()); } @Override public final int hashCode() { return getSymbolName().hashCode(); } /** * Get the symbol name. * @return the symbol name */ public String getSymbolName() { return symbolName; } /** * Get the display name. * @return the display name */ public String getDisplayName() { return displayName; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_util_ParameterInfo.java
1,808
public class PersistedTaxonomyInfo { private String component_id; private boolean puiParent; private String taxoPath; private int obj_version; private int seq_no; /** * Info class for taxonomies. * @param component_id the database id * @param taxoPath the taxonomy path ID * @param puiParent the taxonomy's parent * @param obj_version database object version * @param seq_no database sequence number */ public PersistedTaxonomyInfo(String component_id, String taxoPath, boolean puiParent, int obj_version, int seq_no) { super(); this.component_id = component_id; this.puiParent = puiParent; this.taxoPath = taxoPath; this.obj_version = obj_version; this.seq_no = seq_no; } /** * Get component ID. * @return component ID */ public String getComponent_id() { return component_id; } /** * Set the component ID. * @param component_id component ID */ public void setComponent_id(String component_id) { this.component_id = component_id; } /** * Returns true if this taxonomy is a parent. * @return true if this taxonomy is a parent */ public boolean isPuiParent() { return puiParent; } /** * Set the parent attribute. * @param puiParent the parent */ public void setPuiParent(boolean puiParent) { this.puiParent = puiParent; } /** * Get the taxonomy path ID. * @return taxo path ID */ public String getTaxoPath() { return taxoPath; } /** * Set the taxonomy path ID. * @param taxoPath the path */ public void setTaxoPath(String taxoPath) { this.taxoPath = taxoPath; } /** * Get the object version. * @return object version */ public int getObj_version() { return obj_version; } /** * Set the object version. * @param obj_version the object version */ public void setObj_version(int obj_version) { this.obj_version = obj_version; } /** * Get the sequence number. * @return sequence number */ public int getSeq_no() { return seq_no; } /** * Set the sequence number. * @param seq_no the sequence number */ public void setSeq_no(int seq_no) { this.seq_no = seq_no; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_util_PersistedTaxonomyInfo.java
1,809
public class SQLStatementWriter { /** Enum for dropbox types. */ enum DropboxType {USER, GROUP}; /** Dropbox type. */ DropboxType dropboxType = null; String inputTokensFile; /** * Constructor with type and input file name. * @param type - the dropbox type. * @param f - input file name. */ public SQLStatementWriter(String type, String f) { inputTokensFile = f; dropboxType = type.equals(DropboxType.USER.name()) ? DropboxType.USER : DropboxType.GROUP; } /** * myclient mct --execute="select discipline_id from disciplines;" > /tmp/groupList.txt. * myclient mct --execute="select user_id, discipline_id from mct_users;" > /tmp/userList.txt. * @return map of strings */ private Map<String, String> getTokens() { final Pattern whiteSpace = Pattern.compile("\\s+"); Map<String,String> rv = new LinkedHashMap<String,String>(); try { java.io.BufferedReader stdin = new java.io.BufferedReader(new FileReader(inputTokensFile)); String line = null; while ((line = stdin.readLine()) != null) { if (dropboxType == DropboxType.USER) { String[] ug = whiteSpace.split(line.trim()); rv.put(ug[0], ug[1]); } else{ rv.put(line.trim(), ""); } } } catch (java.io.IOException e) { e.printStackTrace(); } return rv; } private void substitute(Map<String, String> ug) { if (dropboxType == DropboxType.USER) { writeUserStatement(ug); } else { writeGroupStatements(ug); } } private void writeGroupStatements(Map<String, String> ug) { String stmt = null; for (String groupSub : ug.keySet()) { System.out.println("-- "+groupSub); String _disc_ = nextComponentId(); stmt = "set @rootDisciplineId = (SELECT component_id FROM component_spec where external_key = '/Disciplines');"; System.out.println(stmt); stmt = "insert into component_spec (obj_version, component_name, external_key, component_type, model_info, owner, component_id, creator_user_id, date_created) values (0, '_GROUPSUB_', null, 'gov.nasa.arc.mct.core.components.TelemetryDisciplineComponent', null, 'admin', '_disc_','admin', NOW());"; stmt = stmt.replaceAll("_disc_", _disc_).replaceAll("_GROUPSUB_", groupSub); System.out.println(stmt); stmt = "set @parentMaxSeq = ifnull(((SELECT MAX(seq_no) FROM component_relationship where component_id = @rootDisciplineId)) , 0);"; System.out.println(stmt); stmt = "insert into component_relationship (component_id, seq_no, associated_component_id) values (@rootDisciplineId, @parentMaxSeq + 1, '_disc_');"; stmt = stmt.replaceAll("_disc_", _disc_); System.out.println(stmt); stmt = "set @lastObjVersion = (SELECT max(obj_version) FROM component_spec where component_id=@rootDisciplineId);"; System.out.println(stmt); stmt = "update component_spec set obj_version = (@lastObjVersion + 1) where component_id=@rootDisciplineId;"; System.out.println(stmt); } } private void writeUserStatement(Map<String, String> ug) { String stmt = null; stmt = "set @userDropBoxesId = (SELECT component_id FROM component_spec where external_key = '/UserDropBoxes');"; System.out.println(stmt); for (Entry<String, String> ugEntry : ug.entrySet()) { System.out.println("-- "+ ugEntry.getKey()+ " in group "+ugEntry.getValue()); String uuid1 = nextComponentId(); //My Sandbox a child of root stmt = "insert into component_spec (component_name, component_type, model_info, owner, component_id, creator_user_id, date_created) values ('My Sandbox', 'gov.nasa.arc.mct.core.components.MineTaxonomyComponent', null, 'xxUSERxx', 'uuid1', 'xxUSERxx', NOW());"; stmt = stmt.replaceAll("xxUSERxx", ugEntry.getKey()).replaceAll("uuid1", uuid1); System.out.println(stmt); stmt = "insert into tag_association (component_id, tag_id) select component_id, 'bootstrap:creator' from component_spec where component_id = 'uuid1';"; stmt = stmt.replaceAll("uuid1", uuid1); System.out.println(stmt); String uuid2 = nextComponentId(); //a child of My Sandbox and Group's Drop Boxes stmt = "insert into component_spec (component_name, component_type, model_info, owner, component_id, creator_user_id, date_created) values ('xxUSERxx\\'s Drop Box', 'gov.nasa.arc.mct.core.components.TelemetryUserDropBoxComponent', null, '*', 'uuid2', 'xxUSERxx', NOW());"; stmt = stmt.replaceAll("xxUSERxx", ugEntry.getKey()).replaceAll("uuid2", uuid2); System.out.println(stmt); stmt = "insert into component_relationship (component_id, associated_component_id, seq_no) values ('uuid1', 'uuid2', 0);"; stmt = stmt.replaceAll("uuid1", uuid1).replaceAll("uuid2", uuid2); System.out.println(stmt); // Add user dropbox to the User Drop Boxes collection stmt = "set @userDropBoxesMaxSeq = (SELECT COALESCE(MAX(seq_no),0) FROM component_relationship where component_id = @userDropBoxesId);"; System.out.println(stmt); stmt = "insert into component_relationship (component_id, associated_component_id, seq_no) values (@userDropBoxesId, 'uuid2', @userDropBoxesMaxSeq + 1);"; stmt = stmt.replaceAll("uuid2", uuid2); System.out.println(stmt); } } /** * Generates sql code suitable for loading dropboxes. * * For generic base: java gov.nasa.arc.mct.util.SQLStatementWriter USER ../../deployment/src/main/resources/persistence/base/userList.txt > ../../deployment/src/main/resources/persistence/createDropboxesForUsers.sql java gov.nasa.arc.mct.util.SQLStatementWriter GROUP ../../deployment/src/main/resources/persistence/base/groupList.txt > ../../deployment/src/main/resources/persistence/createDropboxesForGroups.sql * * For JSC site: java gov.nasa.arc.mct.util.SQLStatementWriter USER ../../deployment/src/main/resources/site/siteUserList.txt > ../../deployment/src/main/resources/site/dropboxesForUsers.sql java gov.nasa.arc.mct.util.SQLStatementWriter GROUP ../../deployment/src/main/resources/site/siteGroupList.txt > ../../deployment/src/main/resources/site/dropboxesForGroups.sql * * for Orion java gov.nasa.arc.mct.util.SQLStatementWriter USER ../../deployment/src/main/resources/site/orion/siteUserList.txt > ../../deployment/src/main/resources/site/orion/dropboxesForUsers.sql java gov.nasa.arc.mct.util.SQLStatementWriter GROUP ../../deployment/src/main/resources/site/orion/siteGroupList.txt > ../../deployment/src/main/resources/site/orion/dropboxesForGroups.sql * @param args - main method array of arguments. */ public static void main(String args[]) { Map<String, String> tokens = null; if (args.length != 2) { System.out.println("usage: [USER | GROUP] fqUserOrGroupFile "); return; } SQLStatementWriter statementWriter = new SQLStatementWriter(args[0], args[1]); tokens = statementWriter.getTokens(); statementWriter.substitute(tokens); } /** * Gets the next randomly generated Java UUID by replacing all dashes with empty space. * @return UUID - randomly generated Java unique id. */ public static String nextComponentId() { return UUID.randomUUID().toString().replaceAll("-", ""); } }
false
util_src_main_java_gov_nasa_arc_mct_util_SQLStatementWriter.java
1,810
enum DropboxType {USER, GROUP};
false
util_src_main_java_gov_nasa_arc_mct_util_SQLStatementWriter.java
1,811
public class StandardComboBoxColors { private static final Logger logger = LoggerFactory.getLogger(StandardComboBoxColors.class); private Map<String, Color> colorMap; private Map<String, String> defaultSettingsMap; /** Default combo box dimension. */ public static final Dimension COMBO_BOX_DIMENSION = new Dimension(100, 20); /** Default background color name. */ public static final String DEFAULT_BACKGROUND_COLOR = "ColorBG"; /** Button background color. */ public static final String BACKGROUND_COLOR = "ButtonBGColor"; /** Button label foreground color. */ public static final String FOREGROUND_COLOR = "ButtonLabelColor"; /** Text label color. */ public static final String TEXT_LABEL_COLOR = "TextColor"; /** Default foreground color name. */ public static final String DEFAULT_FOREGROUND_COLOR = "ColorFG"; /** Default text label color. */ public static final String DEFAULT_TEXT_LABEL_COLOR = "Color1"; /** Default executables button label text. */ public static final String EXEC_BUTTON_LABEL_TEXT = "LabelText"; /** * Initializes the standard combo box colors maps. */ public StandardComboBoxColors() { initializeColorMap(); initializeDefaultSettingsMap(); logger.debug("new Color(UIManager.getColor(\"Button.background\").getRGB())): {}", new Color(UIManager.getColor("Button.background").getRGB())); logger.debug("new Color(UIManager.getColor(\"Button.foreground\").getRGB())): {}", new Color(UIManager.getColor("Button.foreground").getRGB())); } /** * Creates a new button component. * @param text - the button text label to display. * @return JButton component */ public JButton createJButton(String text) { JButton button = new JButton(text); return button; } /** * Gets the JComponent color properties. * @param comp - the JComponent. * @param colorProperty - The string color property. * @return Color - the color. */ public Color getJComponentColorProps(JComponent comp, String colorProperty) { Color defaultColor = colorMap.get(DEFAULT_BACKGROUND_COLOR); if (colorProperty.equals("Button.background")) { return comp.getBackground(); } else if (colorProperty.equals("Button.foreground")) { return comp.getForeground(); } return defaultColor; } /** * Gets the supported colors. * @return Collection of color. */ public Collection<Color> getSupportedColors() { return colorMap.values(); } /** * Initializes the common color map. */ private void initializeColorMap() { 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)); colorMap.put("ColorBG", new Color(UIManager.getColor("Button.background").getRGB())); colorMap.put("ColorFG", new Color(UIManager.getColor("Button.foreground").getRGB())); } private void initializeDefaultSettingsMap() { defaultSettingsMap = new HashMap<String, String>(); defaultSettingsMap.put(BACKGROUND_COLOR, DEFAULT_BACKGROUND_COLOR); defaultSettingsMap.put(FOREGROUND_COLOR, DEFAULT_FOREGROUND_COLOR); defaultSettingsMap.put(TEXT_LABEL_COLOR, DEFAULT_TEXT_LABEL_COLOR); } /** * Checks whether key is valid or not. * @param key - the key. * @return boolean - flag to check whether key is valid or not. */ public boolean isValidKey(String key) { return defaultSettingsMap.containsKey(key); } /** * Gets the color map. * @return map of colors. */ public Map<String, Color> getColorMap() { return this.colorMap; } /** * Gets the named object. * @param name - the name of the object to fetch. * @return the object to fetch; otherwise null. */ public Object getNamedObject(String name) { if (colorMap.containsKey(name)) { return colorMap.get(name); } return null; } /** * Add key/value pair to color map. * @param colorKey - the color key. * @param colorValue - the color value. */ public void addToColorMap(String colorKey, Color colorValue) { this.colorMap.put(colorKey, colorValue); } /** * Removes the key from the color map. * @param colorKey - the color key. */ public void removeFromColorMap(String colorKey) { this.colorMap.remove(colorKey); } /** * Checks the color key from the default map. * @param colorKey - the color key. */ public void containsColorMapKey(String colorKey) { this.colorMap.containsKey(colorKey); } /** * Checks the color value from the default map. * @param colorValue - the color value. */ public void containsColorMapValue(Color colorValue) { this.colorMap.containsValue(colorValue); } /** * Gets the default setting map. * @return defaultSettingMap - the default setting map. */ public Map<String, String> getDefaultSettingsMap() { return this.defaultSettingsMap; } /** * Adds to default color map settings. * @param key - the color key. * @param value - the color value. */ public void addToDefaultSettingsMap(String key, String value) { this.defaultSettingsMap.put(key, value); } /** * Removes key from the default map settings. * @param key - the color key. */ public void removeFromDefaultSettingsMap(String key) { this.defaultSettingsMap.remove(key); } /** * Checks whether the key is contained in the default map settings. * @param key - the color key. */ public void containsDefaultSettingsMapKey(String key) { this.defaultSettingsMap.containsKey(key); } /** * Checks whether the value is contained in the default map settings. * @param value - the color value. */ public void containsDefaultSettingsMapValue(String value) { this.defaultSettingsMap.containsValue(value); } /** * Color panel layout. * */ public static class ColorPanel extends JPanel { private static final long serialVersionUID = -4129432361356154082L; /** The color instance. */ Color color; /** * Initializes a color panel. * @param c - the color to set to. */ public ColorPanel(Color c) { color = c; setBackground(c); this.setPreferredSize(COMBO_BOX_DIMENSION); } /** * Paints the component. * @param g - Graphics. */ protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(color); g.fillRect(0, 0, getWidth(), getHeight()); } } /** * Implements the gridbag layout with designated constraints. * @param y - integer grid y-coordinates. * @param x - integer grid x-coordinates. * @return GridBagConstraints - gbc */ public GridBagConstraints getConstraints(int y, int x) { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridheight = 1; gbc.gridwidth = 1; gbc.gridx = x; gbc.gridy = y; gbc.weightx = 0.0; gbc.weighty = 0.0; gbc.anchor = GridBagConstraints.NORTHWEST; Insets i = new Insets(2, 2, 2, 2); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = i; return gbc; } }
false
util_src_main_java_gov_nasa_arc_mct_util_StandardComboBoxColors.java
1,812
public static class ColorPanel extends JPanel { private static final long serialVersionUID = -4129432361356154082L; /** The color instance. */ Color color; /** * Initializes a color panel. * @param c - the color to set to. */ public ColorPanel(Color c) { color = c; setBackground(c); this.setPreferredSize(COMBO_BOX_DIMENSION); } /** * Paints the component. * @param g - Graphics. */ protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(color); g.fillRect(0, 0, getWidth(), getHeight()); } }
false
util_src_main_java_gov_nasa_arc_mct_util_StandardComboBoxColors.java
1,813
public class StringUtil { /** * Checks whether the string is empty or not. * @param str - the string to check for * @return boolean - whether string is empty or not. */ public static boolean isEmpty(String str) { return (str == null) || (str.isEmpty()); } /** * Compares two strings. * @param string1 - first string to compare to. * @param string2 - second string to compare to. * @return boolean - comparision flag. */ public static boolean compare(String string1, String string2) { return (string1 != null && string1.equals(string2)) || (string1 == null && string2 == null); } }
false
util_src_main_java_gov_nasa_arc_mct_util_StringUtil.java
1,814
public class StringUtilTest { @Test public void testInstantiation() { Object o = new StringUtil(); assertNotNull(o); } @Test public void testNull() { assertTrue(StringUtil.isEmpty(null)); } @Test public void testEmpty() { assertTrue(StringUtil.isEmpty("")); } @Test public void testLengthOne() { assertFalse(StringUtil.isEmpty("x")); } @Test public void testCompare() { assertTrue(StringUtil.compare(null, null)); assertFalse(StringUtil.compare(null, "hello")); assertFalse(StringUtil.compare("hello", null)); assertTrue(StringUtil.compare("hello", "hello")); assertTrue(StringUtil.compare("", "")); assertFalse(StringUtil.compare("HelLo", "hello")); assertFalse(StringUtil.compare("hello", "hello there")); } }
false
util_src_test_java_gov_nasa_arc_mct_util_StringUtilTest.java
1,815
public class TestClass implements Serializable { /** The serial version ID. */ private static final long serialVersionUID = 1L; /** * A dummy method, just so we have a method to introspect on. * * @return a message */ public String getMessage() { return "hello, world"; } }
false
util_src_test_java_gov_nasa_arc_mct_util_TestClass.java
1,816
public class TreeUtil { /** * Determines whether a point is on a row in a tree, or is outside the tree rows. * @param tree - the JTree. * @param location - Point location. * @return true if the point is on a row. */ public static boolean isPointOnTree(JTree tree, Point location) { return (tree.getRowForLocation(location.x, location.y) != -1); } /** * Checks whether there's a point on the tree. * @param tree - the JTree. * @param x - number. * @param y - number. * @return boolean - flag to check whether the point is on the tree. */ public static boolean isPointOnTree(JTree tree, int x, int y) { return (tree.getRowForLocation(x, y) != -1); } }
false
util_src_main_java_gov_nasa_arc_mct_util_TreeUtil.java
1,817
public class WeakHashSet<T> extends AbstractSet<T> { private static final long serialVersionUID = -7806849276006714321L; private static MCTLogger logger = MCTLogger.getLogger(WeakHashSet.class); private final Map<Integer, WeakEntry<T>> map; private final ReferenceQueue<T> queue = new ReferenceQueue<T>(); /** * Constructor initialization. */ public WeakHashSet() { super(); map = new HashMap<Integer, WeakEntry<T>>(); } /** * Constructor with set. * @param set - the set. */ public WeakHashSet(Set<T> set) { map = new HashMap<Integer, WeakEntry<T>>(); if (set instanceof WeakHashSet<?>) { ((WeakHashSet<T>) set).cleanQueue(); } for (T t : set) { if (t == null) { continue; } map.put(t.hashCode(), new WeakEntry<T>(t, queue)); } } /** * Cleans the queue. */ @SuppressWarnings("unchecked") protected void cleanQueue() { WeakEntry<T> wt; while ((wt = (WeakEntry<T>) queue.poll()) != null) { int hash = wt.hashCode; logger.debug("Garbage collecting: {0}", wt.idString); map.remove(hash); } } /** * Iterates the weak hashset. * @return Iterator<T> - the iterator. */ public Iterator<T> iterator() { cleanQueue(); return new WeakHashSetIterator(map.values().iterator()); } /** * Returns the size of the weak hash set. * @return the size - number. */ public int size() { cleanQueue(); return map.size(); } /** * Checks whether the weak hash set is empty or not. * @return boolean - empty or not. */ public boolean isEmpty() { cleanQueue(); return map.isEmpty(); } /** * Checks whether an object is contained in the hash set. * @param o - the object to check on. * @return boolean - whether the object is contained on the hash set. */ public boolean contains(Object o) { cleanQueue(); return map.containsKey(o.hashCode()); } /** * Adds the designated object to the hash set. * @param o - the object. * @return boolean - returns true if added; otherwise false. */ public boolean add(T o) { cleanQueue(); if (o == null) { return false; } return map.put(o.hashCode(), new WeakEntry<T>(o, queue)) == null; } /** * Removes the designated object from the hash set. * @param o - the object to remove. * @return true if removed; otherwise false. */ public boolean remove(Object o) { return map.remove(o.hashCode()) != null; } /** * Clears the hash set. */ public void clear() { cleanQueue(); map.clear(); } private final class WeakHashSetIterator implements Iterator<T> { private Iterator<WeakEntry<T>> parentIterator; private T nextElement; public WeakHashSetIterator(Iterator<WeakEntry<T>> parentIterator) { this.parentIterator = parentIterator; } @Override public boolean hasNext() { if (nextElement != null) { return true; } boolean hasNext = false; while (!hasNext) { if (!parentIterator.hasNext()) { break; } WeakReference<T> nextRef = parentIterator.next(); nextElement = nextRef.get(); if (nextElement != null) { hasNext = true; } else { parentIterator.remove(); } } return hasNext; } @Override public T next() { if (nextElement != null) { T returnValue = nextElement; nextElement = null; return returnValue; } else if (hasNext()) { T returnValue = nextElement; nextElement = null; return returnValue; } else { throw new NoSuchElementException(); } } @Override public void remove() { parentIterator.remove(); } } private static class WeakEntry<T> extends WeakReference<T> { private final int hashCode; private final String idString; public WeakEntry(T t, ReferenceQueue<T> queue) { super(t, queue); this.hashCode = t.hashCode(); this.idString = t.toString(); } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof WeakEntry)) { return false; } return (this.hashCode == ((WeakEntry<T>) obj).hashCode); } @Override public int hashCode() { return this.hashCode; } } }
false
util_src_main_java_gov_nasa_arc_mct_util_WeakHashSet.java
1,818
private static class WeakEntry<T> extends WeakReference<T> { private final int hashCode; private final String idString; public WeakEntry(T t, ReferenceQueue<T> queue) { super(t, queue); this.hashCode = t.hashCode(); this.idString = t.toString(); } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof WeakEntry)) { return false; } return (this.hashCode == ((WeakEntry<T>) obj).hashCode); } @Override public int hashCode() { return this.hashCode; } }
false
util_src_main_java_gov_nasa_arc_mct_util_WeakHashSet.java
1,819
private final class WeakHashSetIterator implements Iterator<T> { private Iterator<WeakEntry<T>> parentIterator; private T nextElement; public WeakHashSetIterator(Iterator<WeakEntry<T>> parentIterator) { this.parentIterator = parentIterator; } @Override public boolean hasNext() { if (nextElement != null) { return true; } boolean hasNext = false; while (!hasNext) { if (!parentIterator.hasNext()) { break; } WeakReference<T> nextRef = parentIterator.next(); nextElement = nextRef.get(); if (nextElement != null) { hasNext = true; } else { parentIterator.remove(); } } return hasNext; } @Override public T next() { if (nextElement != null) { T returnValue = nextElement; nextElement = null; return returnValue; } else if (hasNext()) { T returnValue = nextElement; nextElement = null; return returnValue; } else { throw new NoSuchElementException(); } } @Override public void remove() { parentIterator.remove(); } }
false
util_src_main_java_gov_nasa_arc_mct_util_WeakHashSet.java
1,820
public class WeakHashSetTest { @Test(expectedExceptions = NoSuchElementException.class) public void emptySetTest() { WeakHashSet<MyReclaimable> hs = new WeakHashSet<MyReclaimable>(); assertEquals(hs.size(), 0); Iterator<MyReclaimable> it = hs.iterator(); it.next(); } @Test public void fromExistingSetTest() { WeakHashSet<MyReclaimable> hs; Set<MyReclaimable> s = new HashSet<MyReclaimable>(); hs = new WeakHashSet<MyReclaimable>(s); assertEquals(hs.size(), 0); assertTrue(hs.isEmpty()); s.add(new MyReclaimable("hello")); hs = new WeakHashSet<MyReclaimable>(s); assertEquals(hs.size(), 1); assertTrue(!hs.isEmpty()); assertTrue(hs.contains(new MyReclaimable("hello"))); Iterator<MyReclaimable> it = hs.iterator(); boolean found = false; while (it.hasNext()) { MyReclaimable value = it.next(); if (value.equals(new MyReclaimable("hello"))) { found = true; } } assertTrue(found); assertTrue(!hs.add(new MyReclaimable("hello"))); assertEquals(hs.size(), 1); assertTrue(hs.add(new MyReclaimable("goodbye"))); assertEquals(hs.size(), 2); assertTrue(!hs.add(new MyReclaimable("goodbye"))); assertEquals(hs.size(), 2); assertTrue(hs.remove(new MyReclaimable("goodbye"))); assertEquals(hs.size(), 1); assertFalse(hs.remove(new MyReclaimable("goodbye"))); assertEquals(hs.size(), 1); hs.clear(); assertEquals(hs.size(), 0); s.clear(); } @Test public void gcTest() throws Exception { WeakHashSet<MyReclaimable> hs; Set<MyReclaimable> s = new HashSet<MyReclaimable>(); s.add(new MyReclaimable("one")); s.add(new MyReclaimable("two")); s.add(new MyReclaimable("three")); hs = new WeakHashSet<MyReclaimable>(s); assertEquals(hs.size(), 3); assertFalse(hs.isEmpty()); s.clear(); Thread.sleep(2000); gc(); Thread.sleep(2000); assertEquals(hs.size(), 0); } private void gc() { Runtime rt = Runtime.getRuntime(); for (int i = 0; i < 3; i++) { try { allocateMemory(1000000); } catch (Throwable th) { } for (int j = 0; j < 3; j++) rt.gc(); } rt.runFinalization(); try { Thread.sleep(50); } catch (Throwable th) { // } } private void allocateMemory(int memAmount) { byte[] big = new byte[memAmount]; // Fight against clever compilers/JVMs that may not allocate // unless we actually use the elements of the array int total = 0; for (int i = 0; i < 10; i++) { // we don't touch all the elements, would take too long. if (i % 2 == 0) total += big[i]; else total -= big[i]; } } private static class MyReclaimable { private final String str; public MyReclaimable(String str) { this.str = str; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof MyReclaimable)) { return false; } MyReclaimable m = (MyReclaimable) obj; return str.equals(m.str); } @Override public int hashCode() { return str.hashCode(); } } }
false
util_src_test_java_gov_nasa_arc_mct_util_WeakHashSetTest.java
1,821
private static class MyReclaimable { private final String str; public MyReclaimable(String str) { this.str = str; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof MyReclaimable)) { return false; } MyReclaimable m = (MyReclaimable) obj; return str.equals(m.str); } @Override public int hashCode() { return str.hashCode(); } }
false
util_src_test_java_gov_nasa_arc_mct_util_WeakHashSetTest.java
1,822
public class AlertBox { public AlertBox() { } /** * Creates alert box for logging * * @param title the title of the alert box * @param msg the alert message * @param format the formating for JOptionPane * @return return the option index the user clicked */ public static Object logBox(String title, String msg, int format) { setLAF(); String[] options = { RStrings.get("CLOSE")}; JOptionPane pane = new JOptionPane(msg, format, JOptionPane.OK_CANCEL_OPTION, null, options); JDialog dialog = pane.createDialog(title); dialog.setVisible(true); return pane.getValue();// waiting for user to close } /** * Sets look and feel for alert box if null */ private static void setLAF() { final MCTProperties mctProperties = MCTProperties.DEFAULT_MCT_PROPERTIES; String laf = mctProperties.getProperty("mct.look.and.feel"); JFrame.setDefaultLookAndFeelDecorated(false); try { UIManager.setLookAndFeel(laf); } catch (Exception e) { e.printStackTrace(); } LookAndFeel current = UIManager.getLookAndFeel(); if (current.getName().equals("Metal")) { UIManager.put("swing.boldMetal", Boolean.FALSE); } } }
false
util_src_main_java_gov_nasa_arc_mct_util_alert_AlertBox.java
1,823
public class LogAlert { private MCTLogger logger; private static MCTLogger alertLog = MCTLogger.getLogger(LogAlert.class); private boolean fork; private final static String DELIMITER = "//"; /** * enum for logging * * @author Blake Arnold * */ public enum Level { DEBUG("Debug"), ERROR("Error"), FATAL("Warning"), WARN("Warning"), INFO( "Information"); private final String name; private Level(String name) { this.name = name; } public String toString() { return name; } }; /** * Initializes log alert * * @param logger * the MCT logger for the class * @param fork * true if you want a new JVM machine for the error, useful if * the awt thread hangs in main program */ public LogAlert(MCTLogger logger, boolean fork) { this.logger = logger; this.fork = fork; } /** * Returns an log alerter * * @param c * class for the alerter * @param fork * true if you want a new JVM machine for the error, useful if * the awt thread hangs in main program * @return LogAlert instance */ public static LogAlert getAlerter(java.lang.Class<?> c, boolean fork) { MCTLogger logger = MCTLogger.getLogger(c); return new LogAlert(logger, fork); } /** * Alerts info * * @param message * message to alert */ public void alertInfo(String message) { alert(formatTitle(0, Level.INFO, null), formatMessage(Level.INFO, message), getMessageType(Level.INFO)); } /** * Alerts a warning * @param title Title for Alert box * @param message * warning message. * */ public void alertWarn(String title, String message) { alertWarn(title, formatMessage(Level.WARN, message), message); } /** * Private method to issue warning alert * @param title title of alert * @param message * @param log */ private void alertWarn(String title, String message, String log) { this.logger.warn(log); alert(title, message, getMessageType(Level.ERROR)); } /** * Alerts a debug * * @param message * debug message * @param t * throwable error message, for logging only */ public void alertDebug(String message, Throwable t) { if (t != null) this.logger.debug(message, t); else this.logger.debug(message); alert(formatTitle(0, Level.DEBUG, null), formatMessage(Level.DEBUG, message), getMessageType(Level.DEBUG)); } /** * Error message * @param title title of message * @param message * Error message * @param t * throwable to log, can be null */ public void alertError(String title, String message, Throwable t) { alertError(title, formatMessage(Level.ERROR, message), message, t); } private void alertError(String title, String message, String log, Throwable t) { if (t != null) this.logger.error(log, t); else this.logger.error(log); alert(title, message, getMessageType(Level.ERROR)); } /** * Fatal Error message * @param title title of alert * @param message * Fatal message * @param t * throwable to log * @param exit * set true if main application needs to be killed */ public void alertFatal(String title, String message, Throwable t, boolean exit) { alertFatal(title, formatMessage(Level.FATAL, message), message, t, exit); } private void alertFatal(String title, String message, String log, Throwable t, boolean exit) { if (t != null) this.logger.fatal(log, t); else this.logger.fatal(log); alert(title, message, getMessageType(Level.FATAL)); if (exit) System.exit(1); } /** * Creates the alert box for the message * * @param l * level of message * @param message * message to alert */ private void alert(String title, String message, int messageType) { if (fork) { String java = javaPath(); try { Runtime.getRuntime().exec( new String[] { java, "-cp", System.getProperty("java.class.path"), "gov.nasa.arc.mct.util.alert.AlertAppl", DELIMITER, title, DELIMITER, message, DELIMITER, Integer.toString(messageType)}); } catch (IOException e) { alertLog.error("Could not run AlertAppl using java path: " + java); } } else { AlertBox.logBox(title, message, messageType); } } /** * determines path to java runtime, changes based on object sharing * * @return java path */ public String javaPath() { final MCTProperties mctProperties = MCTProperties.DEFAULT_MCT_PROPERTIES; String java = mctProperties.getProperty("mct.java.home"); String separator = System.getProperty("file.separator"); java = System.getProperty("java.home"); // removes trailing quotation if (java.charAt(java.length() - 1) == '\"') { java = java.substring(0, java.length() - 1); } // checking for and adding trailing separator in JAVA_HOME if (java.charAt(java.length() - 1) != separator.charAt(0)) { java += separator; } java += "bin" + separator + "java"; return java; } /** * Formats mesage for use when given message * @param l level of message * @param m message * @return */ private static String formatMessage(Level l, String m) { String message = "<html>"; switch (l) { case DEBUG: message += "<B>Debugging with message:</B><br>"; break; case ERROR: message += "<B>An Error has occured with message:</B><br>"; break; case FATAL: message += "<B>A Fatal Error has occured with message:</B><br>"; break; case WARN: message += "<B>Warning</B><br>"; break; case INFO: message += "<B>An error has occured with message:</B><br>"; break; default: message += "<B>MCT " + l.toString() + " with message:</B><br>"; break; } message += " " + m + "<br>" + "<br>" + "See MCT log for more information." + "</html>"; return message; } /** * formats title with error number * @param num number of error * @param l level of error * @param title title of error * @return */ private String formatTitle(int num, Level l, String title) { String t =""; switch (l) { case DEBUG: t += "Debugging" + " - "; break; case ERROR: t += "Error #" + num + " - "; break; case FATAL: t += "Error #" + num + " - "; break; case WARN: t += "Warning #" + num + " - "; break; case INFO: t += "Information #" + num + " - "; break; default: t += "Alert #" + num + " - "; break; } t += title; return t; } /** * Returns integer of message type to use with JOptionPane * @param l level * @return message type */ private int getMessageType(Level l) { int format = JOptionPane.PLAIN_MESSAGE; switch (l) { case DEBUG: format = JOptionPane.INFORMATION_MESSAGE; break; case ERROR: format = JOptionPane.ERROR_MESSAGE; break; case FATAL: format = JOptionPane.ERROR_MESSAGE; break; case WARN: format = JOptionPane.WARNING_MESSAGE; break; case INFO: format = JOptionPane.INFORMATION_MESSAGE; break; default: format = JOptionPane.PLAIN_MESSAGE; break; } return format; } }
false
util_src_main_java_gov_nasa_arc_mct_util_alert_LogAlert.java
1,824
public enum Level { DEBUG("Debug"), ERROR("Error"), FATAL("Warning"), WARN("Warning"), INFO( "Information"); private final String name; private Level(String name) { this.name = name; } public String toString() { return name; } };
false
util_src_main_java_gov_nasa_arc_mct_util_alert_LogAlert.java
1,825
public abstract class Condition { /** * Check whether the condition is satisfied. * * @return true, if the condition is satisfied */ public abstract boolean getValue(); /** * Wait until a given condition becomes true. * * @param maxWait the maximum time to wait, in milliseconds * @param cond the condition we want to wait on * @return true, if the condition is satisfied within the maximum wait time, else false */ public static boolean waitForCondition(long maxWait, Condition cond) { Object signalObject = new Object(); new Condition.PollingThread(cond, maxWait, signalObject).start(); synchronized (signalObject) { try { signalObject.wait(); } catch (InterruptedException e) { // ignore } } return cond.getValue(); } /** * A thread that polls for a condition to be true. Once the condition is satisfied, * notify a specified object that another thread will be waitin on. * * @author mrose * */ public static class PollingThread extends Thread { private Condition cond; long maxWait; Object signalObject; public PollingThread(Condition cond, long maxWait, Object signalObject) { this.cond = cond; this.maxWait = maxWait; this.signalObject = signalObject; } public void run() { long start = System.currentTimeMillis(); for (;;) { try { Thread.sleep(50); } catch (InterruptedException e) { // ignore } long now = System.currentTimeMillis(); if (now-start > maxWait) { break; } if (cond.getValue()) { break; } } synchronized (signalObject) { signalObject.notify(); } } } }
false
tests_src_main_java_gov_nasa_arc_mct_util_condition_Condition.java
1,826
public static class PollingThread extends Thread { private Condition cond; long maxWait; Object signalObject; public PollingThread(Condition cond, long maxWait, Object signalObject) { this.cond = cond; this.maxWait = maxWait; this.signalObject = signalObject; } public void run() { long start = System.currentTimeMillis(); for (;;) { try { Thread.sleep(50); } catch (InterruptedException e) { // ignore } long now = System.currentTimeMillis(); if (now-start > maxWait) { break; } if (cond.getValue()) { break; } } synchronized (signalObject) { signalObject.notify(); } } }
false
tests_src_main_java_gov_nasa_arc_mct_util_condition_Condition.java
1,827
public class ConditionTest { Condition trueCondition = new Condition() { public boolean getValue() { return true; } }; Condition falseCondition = new Condition() { public boolean getValue() { return false; } }; @Test public void testGetValue() throws Exception { assertTrue(trueCondition.getValue()); } @Test public void testAlwaysTrue() throws Exception { Condition.waitForCondition(Long.MAX_VALUE, trueCondition); assertTrue(true, "Condition became true"); } @Test public void testTimeout() throws Exception { Condition.waitForCondition(1000L, falseCondition); assertTrue(!falseCondition.getValue()); assertTrue(true, "Condition timed out"); } @Test public void testChangingCondition() throws Exception { Condition cond = new Condition() { private int intValue = 10; public boolean getValue() { return (--intValue <= 0); } }; Condition.waitForCondition(5000L, cond); assertTrue(cond.getValue()); } }
false
tests_src_test_java_gov_nasa_arc_mct_util_condition_ConditionTest.java
1,828
Condition trueCondition = new Condition() { public boolean getValue() { return true; } };
false
tests_src_test_java_gov_nasa_arc_mct_util_condition_ConditionTest.java
1,829
Condition falseCondition = new Condition() { public boolean getValue() { return false; } };
false
tests_src_test_java_gov_nasa_arc_mct_util_condition_ConditionTest.java
1,830
Condition cond = new Condition() { private int intValue = 10; public boolean getValue() { return (--intValue <= 0); } };
false
tests_src_test_java_gov_nasa_arc_mct_util_condition_ConditionTest.java
1,831
@SuppressWarnings("serial") public class MCTException extends Exception { public MCTException(String s, Throwable e) { super(s); initCause(e); } public MCTException(String s) { super(s); } public MCTException(Throwable e) { super(e); } }
false
util_src_main_java_gov_nasa_arc_mct_util_exception_MCTException.java
1,832
public class MCTExceptionTest { @Test public void testInstantiation() { Exception e; e = new MCTException("the message"); assertNotNull(e); e = new MCTException(new Exception("the message")); assertNotNull(e); e = new MCTException("the message", new Exception("another message")); assertNotNull(e); } }
false
util_src_test_java_gov_nasa_arc_mct_util_exception_MCTExceptionTest.java
1,833
@SuppressWarnings("serial") public class MCTRuntimeException extends RuntimeException { public MCTRuntimeException(String msg, Throwable t) { super(msg, t); } public MCTRuntimeException(String msg) { super(msg); } public MCTRuntimeException(Throwable t) { super(t); } }
false
util_src_main_java_gov_nasa_arc_mct_util_exception_MCTRuntimeException.java
1,834
public class MCTRuntimeExceptionTest { @Test public void testInstantiation() { Exception e; e = new MCTRuntimeException("the message"); assertNotNull(e); e = new MCTRuntimeException(new Throwable("the message")); assertNotNull(e); e = new MCTRuntimeException("the message", new Throwable("another message")); assertNotNull(e); } }
false
util_src_test_java_gov_nasa_arc_mct_util_exception_MCTRuntimeExceptionTest.java
1,835
public class CmdProcessBuilder { private static Logger logger = LoggerFactory.getLogger(CmdProcessBuilder.class); // Sets to not wait since causes the current thread to block. private static final boolean WAIT_PROCESS_EXIT_FLAG = false; private String execSuccessfulMsg = ""; private String execFailedMsg = ""; /** * Default constructor. */ public CmdProcessBuilder() { } /** * Executes external multiple commands. * @param execPath - The execution path. * @param commandList - Array list of commands * @return boolean - flag whether executing multiple commands succeeded. */ public boolean execMultipleCommands(String execPath, List<String> commandList) { boolean execSuccess = false; String errorMsg = ""; if (isUNIXLinux() || isMacOS()) { try { String commandArgs = ""; for (int i=0; i < commandList.size(); i++) { if (i != commandList.size()-1) commandArgs += commandList.get(i) + ","; else commandArgs += commandList.get(i); } logger.debug("commandArgs: " + commandArgs); ProcessBuilder builder = new ProcessBuilder(commandArgs); // Setups default OS specific environment variables if necessary Map<String, String> env = builder.environment(); env.put("EXECDIR", execPath); builder.directory(new File(env.get("EXECDIR"))); logger.debug("Execution Path: " + builder.directory().getAbsolutePath()); Runtime runTime = Runtime.getRuntime(); Process process = runTime.exec(env.get("EXECDIR") + commandArgs); // Prints out any stderror msgs CmdProcessBuilderStreamHelper stdErrorStreamHelper = new CmdProcessBuilderStreamHelper(process.getErrorStream(), "ERROR"); // Prints out any msgs to stdoutput CmdProcessBuilderStreamHelper stdOutputStreamHelper = new CmdProcessBuilderStreamHelper(process.getInputStream(), "OUTPUT"); stdErrorStreamHelper.start(); stdOutputStreamHelper.start(); if (stdErrorStreamHelper.getIOStreamMessages() != null) { logger.info(stdErrorStreamHelper.getIOStreamMessages()); errorMsg = stdErrorStreamHelper.getIOStreamMessages(); } else { logger.error("STDERROR I/O Stream Helper is null: {}", errorMsg); } if (stdOutputStreamHelper.getIOStreamMessages() != null) { logger.info(stdOutputStreamHelper.getIOStreamMessages()); execSuccessfulMsg = stdOutputStreamHelper.getIOStreamMessages(); } else { logger.error("STDOUTPUT I/O Stream Helper is null: {}", execSuccessfulMsg); } if (WAIT_PROCESS_EXIT_FLAG) { int exitValue = process.exitValue(); if (exitValue == 0) { execSuccess = true; logger.info("Command: " + env.get("EXECDIR") + builder.command().toString() + " executed successfully. [Process.exitValue=" + exitValue + "]"); execSuccessfulMsg += "Command: " + env.get("EXECDIR") + builder.command().toString() + " executed successfully. [Process.exitValue=" + exitValue + "]"; } else { execSuccess = false; logger.error("Command: " + env.get("EXECDIR") + builder.command().toString() + " failed because Process.exitValue()=" + exitValue); errorMsg = "Command: " + env.get("EXECDIR") + builder.command().toString() + " failed because Process.exitValue()=" + exitValue; } } else { execSuccess = true; logger.info("Command: " + env.get("EXECDIR") + builder.command().toString() + " executed successfully."); execSuccessfulMsg += "Command: " + env.get("EXECDIR") + builder.command().toString() + " executed successfully."; } } catch(IOException ioe) { logger.error("IOException: ", ioe); errorMsg += ioe.getMessage(); } catch (IllegalArgumentException iae) { logger.error("IllegalArgumentException: ", iae); errorMsg += iae.getMessage(); } if (errorMsg != null && !errorMsg.isEmpty()) execFailedMsg = errorMsg; } else { logger.error(printOSPlatform("Windows OS")); execFailedMsg = printOSPlatform("Windows OS"); } return execSuccess; } /** * Gets the success message after execution attempt. * @return the success message. */ public String getExecSuccessfulMsg() { return execSuccessfulMsg; } /** * Gets the failed message after execution attempt. * @return the failed message. */ public String getExecFailedMsg() { return execFailedMsg; } /** * Tests whether the OS platform execution environment is a Windows, MacOSX, or UNIX/Linux; * because Limit Manager software utility tool (isplimit or limb) is only available in UNIX/Linux. */ /** * Checks for WindowsOS platform. * @return boolean - WindowsOS platform */ public boolean isWindows() { return checkOSPlatform().toLowerCase().contains("windows"); } /** * Checks for MacOS platform. * @return boolean - MacOS platform */ public boolean isMacOS() { return checkOSPlatform().toLowerCase().contains("mac"); } /** * Checks for UNIX/Linux OS platform. * @return boolean - UNIX/Linux OS platform */ public boolean isUNIXLinux() { return checkOSPlatform().toLowerCase().contains("nix") || checkOSPlatform().toLowerCase().contains("nux"); } private String printOSPlatform(String osPlatform) { StringBuffer formatMsg = new StringBuffer(); formatMsg.append("Limit Manager is currently not supported on "); formatMsg.append(osPlatform); formatMsg.append("."); return formatMsg.toString(); } /** * Gets the target OS platform name. * @return OS platform name */ public String checkOSPlatform() { return System.getProperty("os.name"); } /** * For unit testing purposes to set the target OS platform. * @param osName - OS platform */ public void setOSPlatform(String osName) { System.setProperty("os.name", osName); } }
false
util_src_main_java_gov_nasa_arc_mct_util_ext_commands_CmdProcessBuilder.java
1,836
public class CmdProcessBuilderStreamHelper extends Thread { private static Logger logger = LoggerFactory.getLogger(CmdProcessBuilderStreamHelper.class); private InputStream is; // Routes to either I/O stream types stdout or stderr private String type = ""; private InputStreamReader isr; private BufferedReader br; private StringBuffer buffer; /** * Constructor to initialize the input stream and the type. * @param is - input stream. * @param type - I/O stream type. */ public CmdProcessBuilderStreamHelper(InputStream is, String type) { this.is = is; this.type = type; } /** * Run it as thread safe. */ public void run() { try { isr = new InputStreamReader(is); br = new BufferedReader(isr); String line = null; buffer = new StringBuffer(); while ((line = br.readLine()) != null) { if (line != null) { logger.debug("I/O stream type: " + type + " line: " + line); if (!line.isEmpty()) { buffer.append("[" + type + "]: "); buffer.append(line); buffer.append("\n"); } } } } catch (IOException ioe) { logger.error("IOException: ", ioe); } finally { closeAllResources(); } } /** * Gets the I/O stream message if any; else returns null. * @return the I/O stream messages. */ public String getIOStreamMessages() { return buffer == null ? "" : buffer.toString(); } /** * Closes & flushes all I/O streams. */ private void closeAllResources() { close(br, "BufferedReader"); close(isr, "InputStreamReader"); close(is, "InputStream"); } private void close(Closeable c, String exceptionType) { if (c != null) { try { c.close(); } catch (IOException ioe) { logger.warn("[" + exceptionType + "] IOException: ", ioe); } } } }
false
util_src_main_java_gov_nasa_arc_mct_util_ext_commands_CmdProcessBuilderStreamHelper.java
1,837
public class TestCmdProcessBuilder { private CmdProcessBuilder cmdProcessBuilder; @BeforeMethod void setup() { cmdProcessBuilder = new CmdProcessBuilder(); System.setProperty("ExecLimitManagerPath", "src/test/resources/"); System.setProperty("ExecLimitManagerScript", "launchLimitMgrTest.sh"); } @Test public void testOSPlatformSupported() { Assert.assertNotNull(cmdProcessBuilder.checkOSPlatform()); if (cmdProcessBuilder.isWindows()) { cmdProcessBuilder.setOSPlatform("Windows XP"); Assert.assertTrue(cmdProcessBuilder.isWindows()); } if (cmdProcessBuilder.isMacOS()) { cmdProcessBuilder.setOSPlatform("Mac OS X"); Assert.assertTrue(cmdProcessBuilder.isMacOS()); } if (cmdProcessBuilder.isUNIXLinux()) { cmdProcessBuilder.setOSPlatform("Linux"); Assert.assertTrue(cmdProcessBuilder.isUNIXLinux()); } } @Test(dependsOnMethods="testOSPlatformSupported") public void testCmdExecSuccessful() { final String PUI = "TESTCOMMANDPUI"; final List<String> commandList = new ArrayList<String>(); if (cmdProcessBuilder.isMacOS()) { Assert.assertEquals(cmdProcessBuilder.checkOSPlatform(), "Mac OS X"); commandList.add(System.getProperty("ExecLimitManagerScript") + " " + PUI); } else if (cmdProcessBuilder.isUNIXLinux()) { commandList.add(System.getProperty("ExecLimitManagerScript") + " " + PUI); } if (cmdProcessBuilder.isMacOS() || cmdProcessBuilder.isUNIXLinux()) { Assert.assertTrue(cmdProcessBuilder.execMultipleCommands(System.getProperty("ExecLimitManagerPath"), commandList)); } } @Test(dependsOnMethods="testOSPlatformSupported") public void testCmdExecFailed() { final String PUI = "XYZ123abc456"; final List<String> commandList = new ArrayList<String>(); if (cmdProcessBuilder.isUNIXLinux()) { Assert.assertEquals(cmdProcessBuilder.checkOSPlatform(), "Linux"); commandList.add(System.getProperty("ExecLimitManagerScript") + " " + PUI); } else if (cmdProcessBuilder.isMacOS()) { commandList.add(System.getProperty("ExecLimitManagerScript") + " " + PUI); } if (cmdProcessBuilder.isMacOS() || cmdProcessBuilder.isUNIXLinux()) { Assert.assertFalse(cmdProcessBuilder.execMultipleCommands("/wrong/path/", commandList)); } } }
false
util_src_test_java_gov_nasa_arc_mct_util_ext_commands_TestCmdProcessBuilder.java
1,838
public class TestCmdProcessBuilderStreamHelper { private CmdProcessBuilderStreamHelper cmdPBSHelper; private Runtime runTime; private Process process; private int exitValueWaitFor = 1; private int exitValue = 2; private static final String testPUI = "testCOMMANDPUIT"; private CmdProcessBuilder cmdProcessBuilder; @BeforeMethod void setup() { cmdProcessBuilder = new CmdProcessBuilder(); System.setProperty("ExecLimitManagerPath", "src/test/resources/"); System.setProperty("ExecLimitManagerScript", "launchLimitMgrTest.sh"); } @Test public void testGetIOStreamMsgs() { final String execCmd = System.getProperty("ExecLimitManagerPath") + System.getProperty("ExecLimitManagerScript") + " " + testPUI; try { if (cmdProcessBuilder.isMacOS() || cmdProcessBuilder.isUNIXLinux()) { initializeRuntimeProcess(execCmd); cmdPBSHelper = new CmdProcessBuilderStreamHelper(process.getInputStream(), "OUTPUT"); cmdPBSHelper.start(); Assert.assertNotNull(cmdPBSHelper); exitValueWaitFor = process.waitFor(); Assert.assertEquals(0, exitValueWaitFor); exitValue = process.exitValue(); Assert.assertEquals(0, exitValue); } if ((cmdPBSHelper != null) && !cmdPBSHelper.getIOStreamMessages().isEmpty()) { System.out.println("*** " + cmdPBSHelper.getIOStreamMessages()); Assert.assertTrue(cmdPBSHelper.getIOStreamMessages().contains(testPUI)); } } catch (InterruptedException e2) { System.err.println("InterruptedException: " + e2.getMessage()); e2.printStackTrace(); } } @Test public void testIOStreamBuilderHelper() { final String execCmd = System.getProperty("ExecLimitManagerPath") + System.getProperty("ExecLimitManagerScript") + " " + testPUI; try { if (cmdProcessBuilder.isMacOS() || cmdProcessBuilder.isUNIXLinux()) { initializeRuntimeProcess(execCmd); // Prints out any stderror msgs cmdPBSHelper = new CmdProcessBuilderStreamHelper(process.getErrorStream(), "ERROR"); cmdPBSHelper.start(); Assert.assertNotNull(cmdPBSHelper); exitValueWaitFor = process.waitFor(); Assert.assertEquals(0, exitValueWaitFor); exitValue = process.exitValue(); Assert.assertEquals(0, exitValue); } if ((cmdPBSHelper != null) && !cmdPBSHelper.getIOStreamMessages().isEmpty()) { System.err.println(">>> " + cmdPBSHelper.getIOStreamMessages()); Assert.assertTrue(cmdPBSHelper.getIOStreamMessages().contains("ERROR")); } } catch (InterruptedException e2) { System.err.println("InterruptedException: " + e2.getMessage()); e2.printStackTrace(); } } private void initializeRuntimeProcess(String execCmd) { try { runTime = Runtime.getRuntime(); Assert.assertNotNull(runTime); process = runTime.exec(execCmd); Assert.assertNotNull(process); } catch (IOException e1) { System.err.println("IOException: " + e1.getMessage()); e1.printStackTrace(); } } }
false
util_src_test_java_gov_nasa_arc_mct_util_ext_commands_TestCmdProcessBuilderStreamHelper.java
1,839
public class ElapsedTimer { private long overallTime; private long elapsedTimeStart; private long elapsedTimeStop; private long intervals; /** * Default constructor to initialize the overall time and intervals. */ public ElapsedTimer() { overallTime = 0; intervals = 0; } /** * The start time interval. */ public void startInterval() { elapsedTimeStart = getCurrentTime(); elapsedTimeStop = 0; } /** * The stop time interval. */ public void stopInterval() { elapsedTimeStop = getCurrentTime(); intervals++; overallTime += (elapsedTimeStop-elapsedTimeStart); } /** * Gets the number of intervals that have been completed. * @return long time intervals */ public long getIntervals() { return intervals; } /** * Return the last time interval in millis. * @return long time interval in millsecs. */ public long getIntervalInMillis() { return elapsedTimeStop - elapsedTimeStart; } /** * Gets the total time. * @return sum of all interval times in milliseconds */ public long getTotalTime() { return overallTime; } /** * Gets the mean time in double format. * @return double mean time */ public double getMean() { return getTotalTime()/((double)intervals); } /** * Gets the current time in millisecs. * @return current time in millisecs. */ long getCurrentTime() { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } }
false
util_src_main_java_gov_nasa_arc_mct_util_internal_ElapsedTimer.java
1,840
public class ElapsedTimerTest { private ElapsedTimer timer; private long time; @BeforeMethod public void setup() { time = 1; timer = new ElapsedTimer() { @Override long getCurrentTime() { return time; } }; } @Test public void testInterval() { timer.startInterval(); time++; timer.stopInterval(); Assert.assertEquals(timer.getIntervals(), 1); Assert.assertEquals(timer.getTotalTime(), 1); Assert.assertEquals(timer.getIntervalInMillis(), 1); Assert.assertEquals(timer.getMean(), 1.0); } @Test public void testTotalTime() { timer.startInterval(); time++; timer.stopInterval(); time++; timer.startInterval(); time+=2; timer.stopInterval(); Assert.assertEquals(timer.getIntervals(), 2); Assert.assertEquals(timer.getTotalTime(), 3); Assert.assertEquals(timer.getIntervalInMillis(), 2); Assert.assertEquals(timer.getMean(), 1.5); } }
false
util_src_test_java_gov_nasa_arc_mct_util_internal_ElapsedTimerTest.java
1,841
timer = new ElapsedTimer() { @Override long getCurrentTime() { return time; } };
false
util_src_test_java_gov_nasa_arc_mct_util_internal_ElapsedTimerTest.java
1,842
public class MCTLogger { private static final String FQCN = MCTLogger.class.getName(); static final String MCT_LOG_FILE="mct.log.file"; private static boolean initializedAppender = false; private Logger logger; private MCTLogger(Logger logger) { this.logger = logger; } /** * Find or create a logger for MCT subsystem. If a logger has already been * created with the given name it is returned. Otherwise a new logger is * created. * * If a new logger is created it will be configured with MCT central logging. */ public static MCTLogger getLogger(java.lang.Class<?> c) { Logger logger = Logger.getLogger(c); if( !initializedAppender){ initializedAppender= true; initializeAppender((FileAppender) logger.getParent().getAppender("file")); } return new MCTLogger(logger); } /** * Find or create a logger for an MCT subsystem. If a logger has already been created with a * given name it is returned. Otherwise a new logger is created. * @param loggerName to use for the logger * @return logger */ public static MCTLogger getLogger(String loggerName) { return new MCTLogger(Logger.getLogger(loggerName)); } /** * Sets the filename using the value of a system property. * @param fAppender object to modify * */ static void initializeAppender(FileAppender fAppender) { if (fAppender == null) { return; } String newFilename = System.getProperty(MCT_LOG_FILE); if (! StringUtil.isEmpty(newFilename)) { fAppender.setFile(newFilename); fAppender.activateOptions(); } } public void info (Object message) { this.logger.log(FQCN, Level.INFO, message, null); } public void info(String message, Object...params) { log(Level.INFO, message, params); } public void warn (Object message) { this.logger.log(FQCN, Level.WARN, message, null); } public void error (Object message) { this.logger.log(FQCN, Level.ERROR, message, null); } public void error(Object message, Throwable t) { this.logger.log(FQCN, Level.ERROR, message, t); } public void error(Throwable t, String message, Object...params) { this.log(Level.ERROR, t, message, params); } public void debug (Object message) { this.logger.log(FQCN, Level.DEBUG, message, null); } public void debug (Object message, Throwable t) { this.logger.log(FQCN, Level.DEBUG, message, t); } public void warn(Object message, Throwable t) { this.logger.log(FQCN, Level.WARN, message, t); } public void warn(String message, Object...params) { log(Level.WARN, message, params); } public void debug(String message, Object...params) { log(Level.DEBUG, message, params); } private void log(Level l, String message, Object...params) { if (this.logger.isEnabledFor(l)) { String logMessage = MessageFormat.format(message, params); this.logger.log(FQCN,l,logMessage, null); } } private void log(Level l, Throwable t, String message, Object...params) { if (this.logger.isEnabledFor(l)) { String logMessage = MessageFormat.format(message, params); this.logger.log(FQCN, l, logMessage, t); } } public void fatal (Object message) { this.logger.log(FQCN, Level.FATAL, message, null); } public void fatal (Object message, Throwable t) { this.logger.log(FQCN, Level.FATAL, message, t); } }
false
util_src_main_java_gov_nasa_arc_mct_util_logging_MCTLogger.java
1,843
public class MCTLoggerTest { protected final static String msg = "the log message"; MCTLogger logger; Logger baseLogger; boolean saveAdditivity; MyAppender appender; @BeforeClass public void initRootLogger() { saveAdditivity = Logger.getLogger(MCTLoggerTest.class).getAdditivity(); } @AfterClass public void restoreRootLogger() { Logger.getLogger(MCTLoggerTest.class).setAdditivity(saveAdditivity); } @BeforeMethod public void initLogging() { // First get the MCT logger so it will intialize. logger = MCTLogger.getLogger(MCTLoggerTest.class); MCTLogger.getLogger("abc"); // Then get the Log4J logger so we can set up a custom appender. baseLogger = Logger.getLogger(MCTLoggerTest.class); baseLogger.setAdditivity(false); baseLogger.setLevel(Level.ALL); appender = new MyAppender(); baseLogger.removeAllAppenders(); baseLogger.addAppender(appender); } @AfterMethod public void restore() { System.setProperty(MCTLogger.MCT_LOG_FILE, ""); } @Test public void testDebug() throws Exception { logger.debug(msg); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.DEBUG); assertEquals(appender.getEvents().get(0).getMessage(), msg); assertNull(appender.getEvents().get(0).getThrowableInformation()); appender.clearEvents(); logger.debug(msg, new Throwable("exception message")); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.DEBUG); assertEquals(appender.getEvents().get(0).getMessage(), msg); assertNotNull(appender.getEvents().get(0).getThrowableInformation()); appender.clearEvents(); logger.debug("abc {0}", "h"); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.DEBUG); assertEquals(appender.getEvents().get(0).getMessage(), "abc h"); } @Test public void testDebugMessageFormat() throws Exception { logger.info("Hello {0}", "World"); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.INFO); assertEquals(appender.getEvents().get(0).getMessage(), "Hello World"); assertNull(appender.getEvents().get(0).getThrowableInformation()); } @Test public void testInfo() throws Exception { logger.info(msg); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.INFO); assertEquals(appender.getEvents().get(0).getMessage(), msg); assertNull(appender.getEvents().get(0).getThrowableInformation()); } @Test public void testInfoMessageFormat() throws Exception { logger.info("Hello {0}", "World"); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.INFO); assertEquals(appender.getEvents().get(0).getMessage(), "Hello World"); assertNull(appender.getEvents().get(0).getThrowableInformation()); } @Test public void testWarn() throws Exception { logger.warn(msg); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.WARN); assertEquals(appender.getEvents().get(0).getMessage(), msg); assertNull(appender.getEvents().get(0).getThrowableInformation()); } @Test public void testError() throws Exception { logger.error(msg); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.ERROR); assertEquals(appender.getEvents().get(0).getMessage(), msg); assertNull(appender.getEvents().get(0).getThrowableInformation()); appender.clearEvents(); Throwable ex = new Throwable("exception message"); logger.error(msg, ex); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.ERROR); assertEquals(appender.getEvents().get(0).getMessage(), msg); assertNotNull(appender.getEvents().get(0).getThrowableInformation()); } @Test public void testFatal() throws Exception { logger.fatal(msg); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.FATAL); assertEquals(appender.getEvents().get(0).getMessage(), msg); assertNull(appender.getEvents().get(0).getThrowableInformation()); appender.clearEvents(); Throwable ex = new Throwable("exception message"); logger.fatal(msg, ex); assertEquals(appender.getEvents().size(), 1); assertEquals(appender.getEvents().get(0).getLevel(), Level.FATAL); assertEquals(appender.getEvents().get(0).getMessage(), msg); assertNotNull(appender.getEvents().get(0).getThrowableInformation()); } @Test public void testFileAppenderNominal() { FileAppender fa = new FileAppender(); fa.setFile("origFilename"); System.setProperty(MCTLogger.MCT_LOG_FILE, "newFilename"); MCTLogger.initializeAppender(fa); Assert.assertTrue(! fa.getFile().equals("origFilename")); } @Test public void testFileAppenderEmptyProperty() { FileAppender fa = new FileAppender(); fa.setFile("origFilename"); System.setProperty(MCTLogger.MCT_LOG_FILE, ""); MCTLogger.initializeAppender(fa); Assert.assertTrue( fa.getFile().equals("origFilename")); } @Test public void testFileAppenderUnsetProperty() { FileAppender fa = new FileAppender(); fa.setFile("origFilename"); MCTLogger.initializeAppender(fa); Assert.assertTrue( fa.getFile().equals("origFilename")); } @Test public void testFileAppenderError() { System.setProperty(MCTLogger.MCT_LOG_FILE, "newFilename"); MCTLogger.initializeAppender(null); //should not throw Null Pointer } /* * appender for testing written msgs */ protected static class MyAppender extends NullAppender { List<LoggingEvent> events = new ArrayList<LoggingEvent>(); @Override protected void append(LoggingEvent event) { events.add(event); } @Override public void doAppend(LoggingEvent event) { append(event); } public void clearEvents() { events.clear(); } public List<LoggingEvent> getEvents() { return events; } } }
false
util_src_test_java_gov_nasa_arc_mct_util_logging_MCTLoggerTest.java
1,844
protected static class MyAppender extends NullAppender { List<LoggingEvent> events = new ArrayList<LoggingEvent>(); @Override protected void append(LoggingEvent event) { events.add(event); } @Override public void doAppend(LoggingEvent event) { append(event); } public void clearEvents() { events.clear(); } public List<LoggingEvent> getEvents() { return events; } }
false
util_src_test_java_gov_nasa_arc_mct_util_logging_MCTLoggerTest.java
1,845
@SuppressWarnings("serial") public class MCTProperties extends Properties { private static final MCTLogger logger = MCTLogger.getLogger(MCTProperties.class); public static final MCTProperties DEFAULT_MCT_PROPERTIES; static { try { DEFAULT_MCT_PROPERTIES = new MCTProperties(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } } public MCTProperties(String propertyFileName) throws IOException { InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(propertyFileName); if (is == null) throw new IOException("MCT properties util:: Unable to get mct property file: " + propertyFileName); load(is); } public MCTProperties() throws IOException { String defaultProperties = "properties/mct.properties"; InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(defaultProperties); if (is == null) throw new IOException("MCT properties util:: Unable to get mct property file: " + defaultProperties); load(is); } public void load(InputStream is) throws IOException { try { super.load(is); } finally { try { is.close(); } catch (IOException ioe) { // ignore exception } } } /* * get a set of properties named by your class */ public MCTProperties(Class<?> c) throws IOException { String className = getClassName(c); String pkgProperties = "properties/" + className + ".properties"; InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(pkgProperties); if (is == null) throw new IOException("MCT properties util:: Unable to get mct property file: " + pkgProperties); load(is); } /* * returns the class (without the package if any) */ private String getClassName(Class<?> c) { String FQClassName = c.getName(); int firstChar; firstChar = FQClassName.lastIndexOf('.') + 1; if (firstChar > 0) { FQClassName = FQClassName.substring(firstChar); } return FQClassName; } // Normally we could @Override public String getProperty(String key) { String value = System.getProperty(key); if (value != null) { return trim(value); } else { return trim(super.getProperty(key)); } } @Override public String getProperty(String key, String defaultValue) { String value = System.getProperty(key); if (value != null) { return trim(value); } else { return trim(super.getProperty(key,defaultValue)); } } /** * Return a string value trimmed of leading and trailing spaces, or null if the * string is null. * * @param s the string to trim * @return the trimmed value, or null */ protected static String trim(String s) { if (s == null) { return null; } else { return s.trim(); } } }
false
util_src_main_java_gov_nasa_arc_mct_util_property_MCTProperties.java
1,846
public class MCTPropertiesTest { private Properties systemProps; private MCTProperties mctSystemProps = null; private MCTProperties thisPkgProps = null; @BeforeMethod public void makeOurClass () throws IOException { systemProps = (Properties) System.getProperties().clone(); mctSystemProps = new MCTProperties(); thisPkgProps = new MCTProperties(MCTPropertiesTest.class); } @AfterMethod public void restoreProperties() { System.setProperties(systemProps); } @Test public void basicPositiveTest() throws Exception { assertEquals(thisPkgProps.getProperty("test"), "testing789000"); assertEquals(thisPkgProps.size(), 3); assertTrue(mctSystemProps.containsKey("locale")); } @Test public void defaultPropertyTest() throws Exception { String value = null; value = thisPkgProps.getProperty("xxx", "fallbackValue"); assertEquals(value, "fallbackValue"); value = thisPkgProps.getProperty("xxx"); Assert.assertNull(value); } @Test public void stringFileNameTest() throws Exception { MCTProperties props = new MCTProperties("properties/MCTPropertiesTest.properties"); assertNotNull(props); assertTrue(props.containsKey("test")); } public static class MyClass {} @Test(expectedExceptions={java.io.IOException.class}) public void testMissingClassProperties() throws Exception { @SuppressWarnings("unused") MCTProperties props = new MCTProperties(MyClass.class); } @Test(expectedExceptions={java.io.IOException.class}) public void testMissingStringProperties() throws Exception { @SuppressWarnings("unused") MCTProperties props = new MCTProperties("properties/non.existent.properties.file"); } @Test public void testSystemPropertyOverride() throws Exception { System.setProperty("new.property", "new.value"); assertTrue(!thisPkgProps.containsKey("new.property")); assertEquals(thisPkgProps.getProperty("new.property"), "new.value"); assertEquals(thisPkgProps.getProperty("new.property", "default.value"), "new.value"); } @Test public void testTrailingSpaces() { assertEquals(thisPkgProps.getProperty("no_trailing_space_property"), "abc"); assertEquals(thisPkgProps.getProperty("trailing_space_property"), "abc"); assertNull(thisPkgProps.getProperty("no_such_property")); assertEquals(thisPkgProps.getProperty("no_such_property", "abc"), "abc"); assertEquals(thisPkgProps.getProperty("no_such_property", " abc"), "abc"); assertEquals(thisPkgProps.getProperty("no_such_property", "abc "), "abc"); assertEquals(thisPkgProps.getProperty("no_such_property", " abc "), "abc"); } @Test public void testTrim() { assertNull(MCTProperties.trim(null)); assertEquals(MCTProperties.trim(""), ""); assertEquals(MCTProperties.trim("abc"), "abc"); assertEquals(MCTProperties.trim(" abc"), "abc"); assertEquals(MCTProperties.trim("abc "), "abc"); assertEquals(MCTProperties.trim(" abc "), "abc"); } @Test public void testDefaultValue() { // Case 1: no system property, we have file property assertEquals(thisPkgProps.getProperty("test", "abc"), "testing789000"); // Case 2: no system property, no file property assertEquals(thisPkgProps.getProperty("nonExistentSystemProperty", "abc"), "abc"); // Case 3: system property, no file property System.getProperties().put("nonExistentSystemProperty", "xyz"); assertEquals(thisPkgProps.getProperty("nonExistentSystemProperty", "abc"), "xyz"); // Case 4: both system property and file property System.getProperties().put("test", "xyz"); assertEquals(thisPkgProps.getProperty("test", "abc"), "xyz"); } }
false
util_src_test_java_gov_nasa_arc_mct_util_property_MCTPropertiesTest.java
1,847
public static class MyClass {}
false
util_src_test_java_gov_nasa_arc_mct_util_property_MCTPropertiesTest.java
1,848
public class BundleFactory { /** * Return a resource bundle of the given name, either unchanged or * pseudotranslated, depending on the system configuration. * * @param name the name of the bundle to find * @return the bundle * @throws MissingResourceException if the bundle cannot be found */ public static ResourceBundle getBundle(String name) { ResourceBundle baseBundle = ResourceBundle.getBundle(name); if (PseudoBundle.isEnabled()) { return new PseudoBundle(baseBundle); } else { return baseBundle; } } }
false
util_src_main_java_gov_nasa_arc_mct_util_resource_BundleFactory.java
1,849
public class PseudoBundle extends ResourceBundle { /** The system property that controls whether pseudotranslation is used, * and what mode. */ public static final String PSEUDO_BUNDLE_PROPERTY = "mct.pseudotranslation"; /** The property value for normal-width pseudotranslation. */ public static final String PSEUDO_BUNDLE_NORMAL = "normal"; /** The property value for double-width pseudotranslation. */ public static final String PSEUDO_BUNDLE_WIDE = "wide"; /** The possible pseudotranslation modes, normal, wide characters, or none. */ protected enum BundleMode { NORMAL, WIDE, NO_TRANSLATION } /** The pseudotranslation mode. */ private BundleMode mode; /** A message format for bundle keys for which there is no value. */ protected static final String NO_TRANSLATION_FORMAT = "???{0}???"; /** A message format for bundle values that we have pseudotranslated. */ protected static final String TRANSLATED_FORMAT = "\u00AB{0}\u00BB"; /** The base Unicode character in the double-width ASCII set. */ protected static final char FULL_WIDTH_ASCII_BASE = '\uFF01'; /** A map of characters to their translations, for normal-width translation. */ protected static final Map<Character,Character> normalTranslations = new HashMap<Character,Character>(); static { // Some commented out because they don't appear in all of the // fonts Arial, Lucida, and Times. normalTranslations.put('!', '\u00A1'); // inverse ! normalTranslations.put('0', '\u00D8'); // O stroke normalTranslations.put('?', '\u00BF'); // inverse ? normalTranslations.put('A', '\u00C2'); // A hat normalTranslations.put('B', '\u00DF'); // Scharfes Ess normalTranslations.put('C', '\u00C7'); // Capital C cedilla normalTranslations.put('D', '\u00D0'); // D with bar normalTranslations.put('E', '\u00C9'); // E acute // F - no suitable translation normalTranslations.put('G', '\u0120'); // G with dot above normalTranslations.put('H', '\u0124'); // H circumflex normalTranslations.put('I', '\u00CE'); // I hat normalTranslations.put('J', '\u0134'); // J circumflex normalTranslations.put('K', '\u0136'); // K cedilla normalTranslations.put('L', '\u0141'); // L with stroke // M - no suitable translation normalTranslations.put('N', '\u0143'); // N cedilla normalTranslations.put('O', '\u00D6'); // O umlaut normalTranslations.put('P', '\u00DE'); // Thorn // Q - no suitable translation normalTranslations.put('R', '\u0158'); // R with caron normalTranslations.put('S', '\u0160'); // S with caron normalTranslations.put('T', '\u0166'); // T stroke normalTranslations.put('U', '\u00DC'); // U umlaut // V - no suitable translation normalTranslations.put('W', '\u0174'); // W circumflex // X - no suitable translation normalTranslations.put('Y', '\u00A5'); // Yen symbol normalTranslations.put('Z', '\u017B'); // Z with dot above normalTranslations.put('a', '\u00E4'); // a umlaut normalTranslations.put('b', '\u0253'); // b with hook (!) normalTranslations.put('c', '\u00E7'); // c cedilla normalTranslations.put('d', '\u0111'); // d with stroke normalTranslations.put('e', '\u00E9'); // e acute normalTranslations.put('f', '\u0192'); // f with hook normalTranslations.put('g', '\u0123'); // g with cedilla above normalTranslations.put('h', '\u0125'); // h circumflex normalTranslations.put('i', '\u00EF'); // i umlaut normalTranslations.put('j', '\u0135'); // j circumflex normalTranslations.put('k', '\u0137'); // k cedilla normalTranslations.put('l', '\u013C'); // l cedilla // m - no suitable translation normalTranslations.put('n', '\u00F1'); // n tilde normalTranslations.put('o', '\u00F6'); // o umlaut normalTranslations.put('p', '\u00FE'); // thorn // q - no suitable translation normalTranslations.put('r', '\u0159'); // r circumflex normalTranslations.put('s', '\u015D'); // s circumflex normalTranslations.put('t', '\u0167'); // t stroke normalTranslations.put('u', '\u00FC'); // u umlaut // v - no suitable translation normalTranslations.put('w', '\u0175'); // w circumflex normalTranslations.put('x', '\u00D7'); // times normalTranslations.put('y', '\u00FD'); // y acute normalTranslations.put('z', '\u017C'); // z with dot above } /** * Return an indication of whether pseudotranslation is enabled. * * @return true, if pseudotranslation is enabled */ public static boolean isEnabled() { return (getMode() != BundleMode.NO_TRANSLATION); } /** * Return the current pseudotranslation mode by looking at the system * properties. * * @return the current pseudotranslation mode */ protected static BundleMode getMode() { // Look up the system property to set the pseudotranslation mode. String modeString = System.getProperty(PseudoBundle.PSEUDO_BUNDLE_PROPERTY); if (modeString == null) { return BundleMode.NO_TRANSLATION; } else if (modeString.equals(PSEUDO_BUNDLE_NORMAL)) { return BundleMode.NORMAL; } else if (modeString.equals(PSEUDO_BUNDLE_WIDE)) { return BundleMode.WIDE; } else { return BundleMode.NO_TRANSLATION; } } /** The bundle we're wrapping. */ private ResourceBundle baseBundle; /** * Wrap a resource bundle with a pseudotranslated bundle in the current pseudotranslation mode. * * @param baseBundle the bundle to wrap */ public PseudoBundle(ResourceBundle baseBundle) { this.baseBundle = baseBundle; this.mode = getMode(); } @Override public Enumeration<String> getKeys() { return baseBundle.getKeys(); } @Override protected Object handleGetObject(String key) { try { // Try to find the value in the bundle and translate according to the mode. Object value = baseBundle.getObject(key); String stringValue = (String) value; String newValue; switch (mode) { case NORMAL: newValue = translateNormal(stringValue); break; case WIDE: newValue = translateWide(stringValue); break; default: return stringValue; } return MessageFormat.format(TRANSLATED_FORMAT, newValue); } catch (MissingResourceException e) { // No value for the given key. Return a special string with the // property name inside. return MessageFormat.format(NO_TRANSLATION_FORMAT, key); } } /** * Convert a string to double-width ASCII characters. The double-width ASCII set * starts at Unicode position 0xFF01 and has '!' through '~', in the same order * as the ASCII set, so we can do arithmetic to convert each character. * * @param stringValue the value to convert * @return the value converted to double-width ASCII */ protected String translateWide(String stringValue) { boolean inFormat = false; // If true, we're in the middle of a {format} string. StringBuffer result = new StringBuffer(); for (int i=0; i<stringValue.length(); ++i) { char c = stringValue.charAt(i); if (c == '{') { inFormat = true; } if (!inFormat && '!'<=c && c<='~') { result.append((char) (c - '!' + FULL_WIDTH_ASCII_BASE)); } else { result.append(c); } if (c == '}') { inFormat = false; } } return result.toString(); } /** * Convert a string to a normal width pseudotranslation. We use the "normal" * map, defined earlier, to convert each character. Any character not in the * map is left unchanged. * * @param stringValue the value to convert * @return the pseudotranslated value */ protected String translateNormal(String stringValue) { boolean inFormat = false; // If true, we're in the middle of a {format} string. StringBuffer result = new StringBuffer(); for (int i=0; i<stringValue.length(); ++i) { char c = stringValue.charAt(i); if (c == '{') { inFormat = true; } if (!inFormat && normalTranslations.containsKey(c)) { result.append(normalTranslations.get(c)); } else { result.append(c); } if (c == '}') { inFormat = false; } } return result.toString(); } }
false
util_src_main_java_gov_nasa_arc_mct_util_resource_PseudoBundle.java
1,850
protected enum BundleMode { NORMAL, WIDE, NO_TRANSLATION }
false
util_src_main_java_gov_nasa_arc_mct_util_resource_PseudoBundle.java
1,851
public class PseudoBundleTest { private Properties systemProps; @BeforeTest public void saveProperties() { systemProps = System.getProperties(); } @AfterTest public void restoreProperties() { System.setProperties(systemProps); } @Test(expectedExceptions={java.util.MissingResourceException.class}) public void testNonexistentBundle() throws Exception { @SuppressWarnings("unused") ResourceBundle bundle = BundleFactory.getBundle("nonexistent-bundle-name"); } @Test public void testNoProperty() throws Exception { System.setProperties(new Properties()); assertNull(System.getProperty("mct.pseudotranslation")); ResourceBundle origBundle = ResourceBundle.getBundle("properties.PseudoBundle"); ResourceBundle testBundle = BundleFactory.getBundle("properties.PseudoBundle"); assertTrue(!PseudoBundle.isEnabled(), "Pseudotranslation disabled"); assertEquals(origBundle.getString("ascii"), testBundle.getString("ascii")); } @Test public void testNoTranslation() throws Exception { System.setProperty("mct.pseudotranslation", "none"); ResourceBundle origBundle = ResourceBundle.getBundle("properties.PseudoBundle"); ResourceBundle testBundle = BundleFactory.getBundle("properties.PseudoBundle"); assertTrue(!PseudoBundle.isEnabled(), "Pseudotranslation disabled"); assertEquals(origBundle.getString("ascii"), testBundle.getString("ascii")); } @Test public void testNormal() throws Exception { System.setProperty("mct.pseudotranslation", "normal"); ResourceBundle origBundle = ResourceBundle.getBundle("properties.PseudoBundle"); ResourceBundle testBundle = BundleFactory.getBundle("properties.PseudoBundle"); String alphabet = origBundle.getString("alphabet"); String special = origBundle.getString("special"); String noTranslation = origBundle.getString("no_normal_translation"); String ascii = origBundle.getString("ascii"); String translated = testBundle.getString("ascii"); assertTrue(PseudoBundle.isEnabled(), "Pseudotranslation enabled"); // Pseudotranslation adds 1 character of prefix and suffix. assertEquals(ascii.length()+2, translated.length()); for (int i=0; i<ascii.length(); ++i) { char c = ascii.charAt(i); if (noTranslation.indexOf(c) >= 0) { assertEquals(c, translated.charAt(i+1)); } else if (alphabet.indexOf(c)>=0 || special.indexOf(c)>=0) { assertTrue(c != translated.charAt(i+1), "Normal translation changes character " + c); } else { assertEquals(c, translated.charAt(i+1)); } } } @Test public void testWide() { System.setProperty("mct.pseudotranslation", "wide"); ResourceBundle origBundle = ResourceBundle.getBundle("properties.PseudoBundle"); ResourceBundle testBundle = BundleFactory.getBundle("properties.PseudoBundle"); String ascii = origBundle.getString("ascii"); String translated = testBundle.getString("ascii"); assertTrue(PseudoBundle.isEnabled(), "Pseudotranslation enabled"); // Pseudotranslation adds 1 character of prefix and suffix. assertEquals(ascii.length()+2, translated.length()); for (int i=0; i<ascii.length(); ++i) { char c = ascii.charAt(i); assertTrue(c != translated.charAt(i+1), "Wide translation changes character " + c); } } /** Test that we don't translate anything inside a MessageFormat format string. (That is, {...}) */ @Test public void testNormalFormat() { System.setProperty("mct.pseudotranslation", "normal"); ResourceBundle origBundle = ResourceBundle.getBundle("properties.PseudoBundle"); ResourceBundle testBundle = BundleFactory.getBundle("properties.PseudoBundle"); String alphabet = origBundle.getString("alphabet"); String special = origBundle.getString("special"); String noTranslation = origBundle.getString("no_normal_translation"); String messageFormat = origBundle.getString("message_format"); String translated = testBundle.getString("message_format"); assertTrue(PseudoBundle.isEnabled(), "Pseudotranslation enabled"); // Pseudotranslation adds 1 character of prefix and suffix. assertEquals(messageFormat.length()+2, translated.length()); boolean inFormat = false; for (int i=0; i<messageFormat.length(); ++i) { char c = messageFormat.charAt(i); if (c == '{') { inFormat = true; } if (!inFormat && noTranslation.indexOf(c) >= 0) { assertEquals(c, translated.charAt(i+1)); } else if (!inFormat && (alphabet.indexOf(c)>=0 || special.indexOf(c)>=0)) { assertTrue(c != translated.charAt(i+1), "Normal translation changes character " + c); } else { assertEquals(c, translated.charAt(i+1)); } if (c == '}') { inFormat = false; } } } @Test public void testWideFormat() { System.setProperty("mct.pseudotranslation", "wide"); ResourceBundle origBundle = ResourceBundle.getBundle("properties.PseudoBundle"); ResourceBundle testBundle = BundleFactory.getBundle("properties.PseudoBundle"); String messageFormat = origBundle.getString("message_format"); String translated = testBundle.getString("message_format"); assertTrue(PseudoBundle.isEnabled(), "Pseudotranslation enabled"); // Pseudotranslation adds 1 character of prefix and suffix. assertEquals(messageFormat.length()+2, translated.length()); boolean inFormat = false; for (int i=0; i<messageFormat.length(); ++i) { char c = messageFormat.charAt(i); if (c == '{') { inFormat = true; } if (!inFormat && '!'<=c && c<='~') { assertTrue(c != translated.charAt(i+1), "Wide translation changes character " + c); } else { assertEquals(c, translated.charAt(i+1)); } if (c == '}') { inFormat = false; } } } @Test public void testGetKeys() throws Exception { ResourceBundle testBundle = BundleFactory.getBundle("properties.PseudoBundle"); Enumeration<String> e = testBundle.getKeys(); assertNotNull(e); boolean foundAlphabet = false; while (e.hasMoreElements()) { if ("alphabet".equals(e.nextElement())) { foundAlphabet = true; } } assertTrue(foundAlphabet, "Found the 'alphabet' bundle property"); } @Test public void testDirectCreation() { System.setProperty("mct.pseudotranslation", "none"); ResourceBundle origBundle = new PseudoBundle(ResourceBundle.getBundle("properties.PseudoBundle")); ResourceBundle testBundle = BundleFactory.getBundle("properties.PseudoBundle"); assertTrue(!PseudoBundle.isEnabled(), "Pseudotranslation disabled"); assertEquals(origBundle.getString("ascii"), testBundle.getString("ascii")); } @Test public void testMissingResource() { System.setProperty("mct.pseudotranslation", "normal"); ResourceBundle testBundle = BundleFactory.getBundle("properties.PseudoBundle"); String key = "nonexistent.property"; String nonexistent = testBundle.getString(key); assertEquals(nonexistent.length(), key.length()+(2*3)); // 3 '?' on each end assertEquals(nonexistent.substring(3, nonexistent.length()-3), key); } @Test public void testBundleFactoryInstantiation() throws Exception { BundleFactory factory = new BundleFactory(); assertNotNull(factory); } @Test public void testRStrings() throws Exception { System.setProperty("mct.pseudotranslation", "none"); assertEquals(RStrings.CANCEL, "Cancel"); RStrings r = new RStrings(); assertNotNull(r); assertEquals(RStrings.get("CANCEL"), "Cancel"); } }
false
util_src_test_java_gov_nasa_arc_mct_util_resource_PseudoBundleTest.java
1,852
public class RStrings { private final static ResourceBundle bundle = BundleFactory.getBundle("properties.RStrings"); public final static String CANCEL = bundle.getString("CANCEL"); public final static String CLOSE = bundle.getString("CLOSE"); public final static String CREATE = bundle.getString("CREATE"); public final static String OK = bundle.getString("OK"); public final static String LAYOUT_C = bundle.getString("LAYOUT_C"); public final static String SHOW = bundle.getString("SHOW"); public final static String SHOW_ALL = bundle.getString("SHOW_ALL"); public final static String EXTENDED_CONTROL_AREA = bundle.getString("EXTENDED_CONTROL_AREA"); public final static String LEGENDS = bundle.getString("LEGENDS"); public final static String LINES = bundle.getString("LINES"); public final static String NAMES = bundle.getString("NAMES"); public final static String PUIS= bundle.getString("PUIS"); public final static String UNITS = bundle.getString("UNITS"); public final static String PRINT_DOT = bundle.getString("PRINT_DOT"); public final static String EXPORT_DOT = bundle.getString("EXPORT_DOT"); public final static String CLEAR_PLOT = bundle.getString("CLEAR_PLOT"); /** * Use this method if new resource strings are to be added without changing this class. * @param key the key to the desired resource string * @return the string corresponding to the key */ public static String get(String key) { return bundle.getString(key); } }
false
util_src_main_java_gov_nasa_arc_mct_util_resource_RStrings.java
1,853
public class CreateExecutableButtonComponentWizardUI extends CreateWizardUI { private static final ResourceBundle bundle = ResourceBundle.getBundle("ResourceBundle"); //NOI18N private final JTextField baseDisplayName = new JTextField(); private final JTextField execCommand = new JTextField(); @Override public AbstractComponent createComp(ComponentRegistry comp, AbstractComponent targetComponent) { String displayName = baseDisplayName.getText().trim(); String execCmd = execCommand.getText().trim(); AbstractComponent component = null; component = comp.newInstance(ExecutableButtonComponent.class, targetComponent); ExecutableButtonModel execButtonModel = ExecutableButtonComponent.class.cast(component).getModel(); execButtonModel.getData().setExecCmd(execCmd); component.setDisplayName(displayName); component.save(); return component; } private void setupTextField(String defaultValue, final JTextField field, final JButton create) { field.setText(defaultValue); //NOI18N field.selectAll(); field.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { } @Override public void insertUpdate(DocumentEvent e) { doAction(); } @Override public void removeUpdate(DocumentEvent e) { doAction(); } private boolean verify(String input) { return input != null && !input.trim().isEmpty(); } private void doAction() { boolean flag = verify(execCommand.getText().trim()) && verify(baseDisplayName.getText().trim()); create.setEnabled(flag); } }); } @Override public JComponent getUI(final JButton create) { JLabel baseDisplayNameLabel = new JLabel(bundle.getString("BASE_DISPLAY_NAME_LABEL")); //NOI18N setupTextField(bundle.getString("DEFAULT_BDN_LABEL"), baseDisplayName, create); baseDisplayNameLabel.setLabelFor(baseDisplayName); baseDisplayName.requestFocus(); baseDisplayName.setToolTipText(bundle.getString("BDN_TOOL_TIP")); JLabel execCommandLabel = new JLabel(bundle.getString("EXEC_COMMAND_LABEL")); //NOI18N setupTextField("", execCommand, create); execCommand.setToolTipText(bundle.getString("EXEC_CMD_TOOL_TIP")); execCommandLabel.setLabelFor(execCommand); JPanel messagePanel = new JPanel(); JPanel UIPanel = new JPanel(); UIPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridheight = 1; c.anchor = GridBagConstraints.SOUTHEAST; c.gridy = 0; c.gridx = 0; c.fill = GridBagConstraints.NONE; c.weightx = 0.0; c.insets = new Insets (0,5,5,0); UIPanel.add(baseDisplayNameLabel, c); c.gridx = 1; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.NORTHWEST; c.insets = new Insets (5,5,5,5); UIPanel.add(baseDisplayName, c); c.gridx = 0; c.gridy = 1; c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.SOUTHEAST; c.insets = new Insets (0,5,0,0); c.weightx = 0; UIPanel.add(execCommandLabel, c); c.gridx = 1; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.NORTHWEST; c.insets = new Insets(0,5,0,5); UIPanel.add(execCommand, c); c.gridx = 0; c.gridy = 2; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; c.gridwidth = 2; UIPanel.add(messagePanel,c); UIPanel.setVisible(true); return UIPanel; } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_CreateExecutableButtonComponentWizardUI.java
1,854
field.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { } @Override public void insertUpdate(DocumentEvent e) { doAction(); } @Override public void removeUpdate(DocumentEvent e) { doAction(); } private boolean verify(String input) { return input != null && !input.trim().isEmpty(); } private void doAction() { boolean flag = verify(execCommand.getText().trim()) && verify(baseDisplayName.getText().trim()); create.setEnabled(flag); } });
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_CreateExecutableButtonComponentWizardUI.java
1,855
public class ExecutableButtonComponent extends AbstractComponent { private static final ResourceBundle bundle = ResourceBundle.getBundle("ResourceBundle"); //NOI18N private final AtomicReference<ExecutableButtonModel> model = new AtomicReference<ExecutableButtonModel>(new ExecutableButtonModel()); @Override protected <T> T handleGetCapability(Class<T> capability) { if (ModelStatePersistence.class.isAssignableFrom(capability)) { JAXBModelStatePersistence<ExecutableButtonModel> persistence = new JAXBModelStatePersistence<ExecutableButtonModel>() { @Override protected ExecutableButtonModel getStateToPersist() { return model.get(); } @Override protected void setPersistentState(ExecutableButtonModel modelState) { model.set(modelState); } @Override protected Class<ExecutableButtonModel> getJAXBClass() { return ExecutableButtonModel.class; } }; return capability.cast(persistence); } return null; } @Override public boolean isLeaf() { return true; } public ExecutableButtonModel getModel() { return model.get(); } @Override public List<PropertyDescriptor> getFieldDescriptors() { PropertyDescriptor p = new PropertyDescriptor(bundle.getString("EXEC_COMMAND_LABEL"), new ExecutableButtonEditor(this), VisualControlDescriptor.TextField); p.setFieldMutable(true); return Collections.singletonList(p); } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_ExecutableButtonComponent.java
1,856
JAXBModelStatePersistence<ExecutableButtonModel> persistence = new JAXBModelStatePersistence<ExecutableButtonModel>() { @Override protected ExecutableButtonModel getStateToPersist() { return model.get(); } @Override protected void setPersistentState(ExecutableButtonModel modelState) { model.set(modelState); } @Override protected Class<ExecutableButtonModel> getJAXBClass() { return ExecutableButtonModel.class; } };
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_ExecutableButtonComponent.java
1,857
public class ExecutableButtonComponentProvider extends AbstractComponentProvider { private static final ResourceBundle bundle = ResourceBundle.getBundle("ResourceBundle"); private final AtomicReference<ComponentTypeInfo> executableButtonComponentType = new AtomicReference<ComponentTypeInfo>(); private final AtomicReference<RoleService> roleService = new AtomicReference<RoleService>(); private static final String OBJECTS_CREATE_EXT_PATH = "/objects/creation.ext"; private static final String THIS_EXECUTE_PATH = "/this/additions"; private static final String EXECUTABLE_BUTTON_ACTION_MENU = "EXECUTABLE_BUTTON_ACTION"; private static final String EXECUTABLE_BUTTON_THIS_MENU = "EXECUTABLE_BUTTON_THIS"; private ComponentTypeInfo createTypeInfo() { User user = PlatformAccess.getPlatform().getCurrentUser(); RoleService rs = roleService.get(); boolean superUser = rs.hasRole(user, "GA") || rs.hasRole(user, "DTR"); if (!superUser) { return new ComponentTypeInfo( bundle.getString("display_name"), bundle.getString("description"), ExecutableButtonComponent.class, false, new ImageIcon(ExecutableButtonComponent.class.getResource("/icons/executableIcon.png")) ); } return new ComponentTypeInfo( bundle.getString("display_name"), bundle.getString("description"), ExecutableButtonComponent.class, new CreateExecutableButtonComponentWizardUI(), new ImageIcon(ExecutableButtonComponent.class.getResource("/icons/executableIcon.png")) ); } public void setRoleService(RoleService aRoleService) { roleService.set(aRoleService); executableButtonComponentType.set(createTypeInfo()); } public void releaseRoleService(RoleService aRolesService) { roleService.set(null); } @Override public Collection<ComponentTypeInfo> getComponentTypes() { return Collections.singleton(executableButtonComponentType.get()); } @Override public Collection<ViewInfo> getViews(String componentTypeId) { if (componentTypeId.equals(ExecutableButtonComponent.class.getName())) { Collection<ViewInfo> views = new ArrayList<ViewInfo>(); views.add(new ViewInfo(ExecutableButtonManifestation.class, ExecutableButtonManifestation.VIEW_NAME, ViewType.OBJECT)); views.add(new ViewInfo(ExecutableButtonManifestation.class, ExecutableButtonManifestation.VIEW_NAME, ExecutableButtonManifestation.class.getName(), ViewType.EMBEDDED, new ImageIcon(getClass().getResource("/icons/executableViewButton-OFF.png")), new ImageIcon(getClass().getResource("/icons/executableViewButton-ON.png")))); return views; } return Collections.emptyList(); } @Override public Collection<MenuItemInfo> getMenuItemInfos() { return Arrays.asList( new MenuItemInfo( OBJECTS_CREATE_EXT_PATH, EXECUTABLE_BUTTON_ACTION_MENU, MenuItemType.NORMAL, ExecutableButtonAction.class), new MenuItemInfo( THIS_EXECUTE_PATH, EXECUTABLE_BUTTON_THIS_MENU, MenuItemType.NORMAL, ExecutableButtonThisAction.class) ); } @Override public Collection<PolicyInfo> getPolicyInfos() { return Collections.singleton(new PolicyInfo(PolicyInfo.CategoryType.PREFERRED_VIEW.getKey(), ExecutableButtonViewPolicy.class)); } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_ExecutableButtonComponentProvider.java
1,858
public final class ExecutableButtonEditor implements PropertyEditor<Object> { ExecutableButtonComponent executableButtonComponent = null; public ExecutableButtonEditor(ExecutableButtonComponent comp) { executableButtonComponent = comp; } @Override public String getAsText() { return executableButtonComponent.getModel().getData().getExecCmd(); } /** * Edit the value of a limit line. * Refresh the value of the cache, so that GUIs like plot and alpha are redrawn. * * @param newValue the new limit line value * @throws exception if the new value is invalid. The consumer must handle this exception and * disallow the prospective edit. */ @Override public void setAsText(String newValue) throws IllegalArgumentException { if (newValue == null || newValue.isEmpty()) { throw new IllegalArgumentException("Cannot be empty."); } executableButtonComponent.getModel().getData().setExecCmd(newValue); } @Override public Object getValue() { throw new UnsupportedOperationException(); } @Override public void setValue(Object value) { throw new UnsupportedOperationException(); } @Override public List<Object> getTags() { throw new UnsupportedOperationException(); } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_ExecutableButtonEditor.java
1,859
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class ExecutableButtonModel { private ExecutableButtonPersistData execButtonPersistData = new ExecutableButtonPersistData(); public ExecutableButtonPersistData getData() { return execButtonPersistData; } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_ExecutableButtonModel.java
1,860
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class ExecutableButtonPersistData { private String execCmd; public String getExecCmd() { return this.execCmd; } public void setExecCmd(String execCmd) { this.execCmd = execCmd; } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_ExecutableButtonPersistData.java
1,861
public class ExecutableButtonSettings { private ExecutableButtonManifestation manifestation; private Map<String, Color> colorMap; private Map<Object, String> reverseMap; private Map<String, String> defaultSettingsMap; private StandardComboBoxColors stdComboBoxColors; public static final int LABEL_TEXT_SIZE = 20; public ExecutableButtonSettings (ExecutableButtonManifestation manifestation) { this.manifestation = manifestation; initializeStandardComboBoxColors(); reverseMap = new HashMap<Object, String>(); addToReverseMap(colorMap); } public void initializeStandardComboBoxColors() { stdComboBoxColors = new StandardComboBoxColors(); colorMap = stdComboBoxColors.getColorMap(); defaultSettingsMap = stdComboBoxColors.getDefaultSettingsMap(); } private void addToReverseMap(Map<String, ?> map) { for (Entry<String, ?> e : map.entrySet()) { reverseMap.put(e.getValue(), e.getKey()); } } public List<Color> getSavedColors() { List<Color> colors = new ArrayList<Color>(); colors.add((Color) getSetting(StandardComboBoxColors.BACKGROUND_COLOR)); colors.add((Color) getSetting(StandardComboBoxColors.FOREGROUND_COLOR)); return colors; } public void updateManifestation() { manifestation.buildFromSettings(); manifestation.getManifestedComponent().save(); } public Object getSetting(String name) { String choice = getProps(name); if (colorMap.containsKey(choice)) { return colorMap.get(choice); } else { return choice; } } public boolean isValidKey(String key) { return defaultSettingsMap.containsKey(key); } public String getProps(String key) { String value = manifestation.getViewProperties().getProperty(key, String.class); if (value == null) { if (!stdComboBoxColors.isValidKey(key)) { return null; } setProps(key, defaultSettingsMap.get(key)); value = defaultSettingsMap.get(key); } return value; } public void setProps(String key, String value) { ExtendedProperties viewProperties = manifestation.getViewProperties(); viewProperties.setProperty(key, value); } public void setByObject (String key, Object value) { if (reverseMap.containsKey(value)) { setProps(key, reverseMap.get(value)); } else if (value instanceof String) { setProps(key, (String) value); } } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_ExecutableButtonSettings.java
1,862
public class ExecutableButtonViewPolicy implements Policy { @Override public ExecutionResult execute(PolicyContext context) { boolean result = true; ViewInfo viewInfo = context.getProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), ViewInfo.class); if (ExecutableButtonManifestation.class.equals(viewInfo.getViewClass())) { AbstractComponent targetComponent = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), ExecutableButtonComponent.class); result = !ExecutableButtonComponent.class.isAssignableFrom(targetComponent.getClass()); } return new ExecutionResult(context, result, null); } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_ExecutableButtonViewPolicy.java
1,863
@SuppressWarnings("serial") public class ExecutableButtonControlPanel extends JPanel { private static final Logger logger = LoggerFactory.getLogger(ExecutableButtonControlPanel.class); private static final ResourceBundle bundle = ResourceBundle.getBundle("ResourceBundle"); private ExecutableButtonSettings execButtonSettings; private ExecutableButtonManifestation manifestation; private JLabel buttonLabel; private JLabel buttonLabelColor; private JLabel buttonBGColor; private JTextField buttonField; private String buttonText; private JComboBox buttonColorComboBox; private JComboBox buttonBGColorComboBox; private Map<String, Color> colorMap; private Map<String, String> defaultSettingsMap; private JPanel mainComponent; private StandardComboBoxColors stdComboBoxColors; public ExecutableButtonControlPanel(ExecutableButtonManifestation manifestation) { this.manifestation = manifestation; initializeStandardComboBoxColors(); execButtonSettings = manifestation.getSettings(); buildView(manifestation); } private void initializeStandardComboBoxColors() { stdComboBoxColors = new StandardComboBoxColors(); colorMap = stdComboBoxColors.getColorMap(); defaultSettingsMap = stdComboBoxColors.getDefaultSettingsMap(); logger.debug("colorMap: {}", colorMap); } private void buildView(ExecutableButtonManifestation manifestation) { this.setLayout(new FlowLayout(FlowLayout.LEADING)); this.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); mainComponent = new JPanel(new GridBagLayout()); mainComponent.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); mainComponent.setAlignmentY(TOP_ALIGNMENT); mainComponent.setAlignmentX(LEFT_ALIGNMENT); if (execButtonSettings.getSetting(StandardComboBoxColors.EXEC_BUTTON_LABEL_TEXT) != null) { buttonText = (String)execButtonSettings.getSetting(StandardComboBoxColors.EXEC_BUTTON_LABEL_TEXT); } buttonField = new JTextField(buttonText, ExecutableButtonSettings.LABEL_TEXT_SIZE); buttonField.setToolTipText(buttonText); buttonField.setEditable(true); buttonField.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { String currentText = buttonField.getText(); if (currentText != null) { currentText = currentText.trim(); } if (!currentText.equals(buttonText)) { saveSettings(StandardComboBoxColors.EXEC_BUTTON_LABEL_TEXT, currentText); buttonText = currentText; } } @Override public void focusGained(FocusEvent e) { } }); buttonField.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent keyEvt) { int key = keyEvt.getKeyCode(); if ( (key == KeyEvent.VK_ENTER) || (key == KeyEvent.VK_TAB) ) { saveSettings(StandardComboBoxColors.EXEC_BUTTON_LABEL_TEXT, buttonField.getText()); } } @Override public void keyReleased(KeyEvent keyEvt) { } @Override public void keyTyped(KeyEvent keyEvt) { } }); instrumentNamesForButtonLabel(); buttonColorComboBox = makeComboBox("ButtonLabelColor", stdComboBoxColors.getSupportedColors()); buttonBGColorComboBox = makeComboBox("ButtonBGColor", stdComboBoxColors.getSupportedColors()); buttonLabel = new JLabel(bundle.getString("ButtonLabel")); buttonLabel.setLabelFor(buttonField); buttonLabelColor = new JLabel(bundle.getString("ButtonLabelColor")); buttonLabelColor.setLabelFor(buttonColorComboBox); buttonBGColor = new JLabel(bundle.getString("ButtonBGColor")); buttonBGColor.setLabelFor(buttonBGColorComboBox); instrumentLabelNames(); mainComponent.add(buttonLabel, stdComboBoxColors.getConstraints(1,0)); mainComponent.add(buttonField, stdComboBoxColors.getConstraints(1,1)); mainComponent.add(buttonLabelColor, stdComboBoxColors.getConstraints(2,0)); mainComponent.add(buttonColorComboBox, stdComboBoxColors.getConstraints(2,1)); mainComponent.add(buttonBGColor, stdComboBoxColors.getConstraints(3,0)); mainComponent.add(buttonBGColorComboBox, stdComboBoxColors.getConstraints(3,1)); add(mainComponent, BorderLayout.NORTH); } private void saveSettings(String name, String text) { execButtonSettings.setByObject(name, text); execButtonSettings.updateManifestation(); } private void instrumentLabelNames() { buttonLabel.getAccessibleContext().setAccessibleName("buttonLabel"); buttonLabelColor.getAccessibleContext().setAccessibleName("buttonLabelColor"); buttonBGColor.getAccessibleContext().setAccessibleName("buttonBGColor"); } public Object getSetting(String name) { String choice = getProps(name); if (colorMap.containsKey(choice)) { return colorMap.get(choice); } else { return choice; } } private boolean isValidKey(String key) { return defaultSettingsMap.containsKey(key); } private String getProps(String key) { String value = manifestation.getViewProperties().getProperty(key, String.class); if (value == null) { if (!isValidKey(key)) return null; setProps(key, defaultSettingsMap.get(key)); value = defaultSettingsMap.get(key); } return value; } private void setProps(String key, String value) { ExtendedProperties viewProperties = manifestation.getViewProperties(); viewProperties.setProperty(key, value); } private JComboBox makeComboBox(String name, Collection<?> items) { JComboBox box = new JComboBox (items.toArray()); box.setName(name); box.setRenderer(new ListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object obj, int arg2, boolean arg3, boolean arg4) { if (obj instanceof Color) { return new StandardComboBoxColors.ColorPanel((Color) obj); } return new JPanel(); } }); Object selected = execButtonSettings.getSetting(name); if (selected != null) { box.setSelectedItem(selected); } else if (items.size() > 0) { box.setSelectedIndex(0); } box.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JComponent comp = (JComponent)evt.getSource(); Object value = null; String name = comp.getName(); if (comp instanceof JComboBox) { value = ((JComboBox) comp).getSelectedItem(); } if (value != null) { execButtonSettings.setByObject(name, value); execButtonSettings.updateManifestation(); } } }); return box; } private void instrumentNamesForButtonLabel() { buttonField.getAccessibleContext().setAccessibleName("buttonLabelTextField"); } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_view_ExecutableButtonControlPanel.java
1,864
buttonField.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { String currentText = buttonField.getText(); if (currentText != null) { currentText = currentText.trim(); } if (!currentText.equals(buttonText)) { saveSettings(StandardComboBoxColors.EXEC_BUTTON_LABEL_TEXT, currentText); buttonText = currentText; } } @Override public void focusGained(FocusEvent e) { } });
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_view_ExecutableButtonControlPanel.java
1,865
buttonField.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent keyEvt) { int key = keyEvt.getKeyCode(); if ( (key == KeyEvent.VK_ENTER) || (key == KeyEvent.VK_TAB) ) { saveSettings(StandardComboBoxColors.EXEC_BUTTON_LABEL_TEXT, buttonField.getText()); } } @Override public void keyReleased(KeyEvent keyEvt) { } @Override public void keyTyped(KeyEvent keyEvt) { } });
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_view_ExecutableButtonControlPanel.java
1,866
box.setRenderer(new ListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object obj, int arg2, boolean arg3, boolean arg4) { if (obj instanceof Color) { return new StandardComboBoxColors.ColorPanel((Color) obj); } return new JPanel(); } });
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_view_ExecutableButtonControlPanel.java
1,867
box.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JComponent comp = (JComponent)evt.getSource(); Object value = null; String name = comp.getName(); if (comp instanceof JComboBox) { value = ((JComboBox) comp).getSelectedItem(); } if (value != null) { execButtonSettings.setByObject(name, value); execButtonSettings.updateManifestation(); } } });
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_view_ExecutableButtonControlPanel.java
1,868
@SuppressWarnings("serial") public class ExecutableButtonManifestation extends View { private static final Logger logger = LoggerFactory.getLogger(ExecutableButtonManifestation.class); private static final Logger ADVISORY_LOGGER = LoggerFactory.getLogger("gov.nasa.jsc.advisory.service"); private static final ResourceBundle bundle = ResourceBundle.getBundle("ResourceBundle"); private static final int MAX_BASE_DISPLAY_NAME_LENGTH = 30; private static final String ELLIPSE = "..."; private ExecutableButtonModel execButtonModel; private JButton execButton; private String execCmd; private String baseDisplayName; private AbstractComponent component; public static final String VIEW_NAME = bundle.getString("ViewRoleName"); private ExecutableButtonSettings execButtonSettings; private List<Color> colorList = new ArrayList<Color>(); private String labelText; private ExecutableButtonControlPanel execButtonControlPanel; public ExecutableButtonManifestation(AbstractComponent ac, ViewInfo vi) { super(ac,vi); setBackground(UIManager.getColor("background")); execButtonSettings = new ExecutableButtonSettings(this); this.setOpaque(true); createExecButtons(); } public ExecutableButtonSettings getSettings() { return execButtonSettings; } @Override protected JComponent initializeControlManifestation() { initializeExecButtonControlPanel(); return new JScrollPane(execButtonControlPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); } private void initializeExecButtonControlPanel() { execButtonControlPanel = new ExecutableButtonControlPanel(this); } public List<Color> getSavedColorList() { return colorList; } public void buildFromSettings() { colorList = execButtonSettings.getSavedColors(); logger.debug("Saved settings colorList: {}", colorList); if ( (execButtonSettings.getSetting(StandardComboBoxColors.EXEC_BUTTON_LABEL_TEXT) != null) && !((String)execButtonSettings.getSetting(StandardComboBoxColors.EXEC_BUTTON_LABEL_TEXT)).isEmpty()) { labelText = (String)execButtonSettings.getSetting(StandardComboBoxColors.EXEC_BUTTON_LABEL_TEXT); execButton.setText(labelText); } else { if (baseDisplayName == null) { execButton.setText(""); logger.error("Base Display Name is NULL."); } else { execButton.setText(baseDisplayName); } } if (execButtonSettings.getSetting(StandardComboBoxColors.BACKGROUND_COLOR) != null) { execButton.setBackground((Color)execButtonSettings.getSetting(StandardComboBoxColors.BACKGROUND_COLOR)); } if (execButtonSettings.getSetting(StandardComboBoxColors.FOREGROUND_COLOR) != null) { execButton.setForeground((Color)execButtonSettings.getSetting(StandardComboBoxColors.FOREGROUND_COLOR)); } } private void createExecButtons() { Rectangle bounds = this.getBounds().getBounds(); int padding = Math.min(bounds.width, bounds.height) / 20; bounds.grow(-padding, -padding); component = getManifestedComponent(); execButtonModel = ExecutableButtonComponent.class.cast(getManifestedComponent()).getModel(); execCmd = execButtonModel.getData().getExecCmd(); baseDisplayName = component.getDisplayName(); if (execCmd != null) { execCmd = execCmd.trim(); } if (baseDisplayName != null) { baseDisplayName = baseDisplayName.trim(); } String cmdLine = "Exec Cmd: " + execCmd; if (baseDisplayName.length() > MAX_BASE_DISPLAY_NAME_LENGTH) { baseDisplayName = baseDisplayName.substring(0, MAX_BASE_DISPLAY_NAME_LENGTH) + ELLIPSE; } execButton = new JButton(baseDisplayName); execButton.setBounds(bounds); execButton.setToolTipText(cmdLine); execButton.setActionCommand(execCmd); buildFromSettings(); logger.debug("execButton.getBackground(): " + execButton.getBackground() + ", execButton.getForeground(): " + execButton.getForeground() + ", execButton.getColorModel(): " + execButton.getColorModel()); execButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { buttonPressed(); } }); setLayout(new BorderLayout()); add(execButton, BorderLayout.CENTER); if (execButtonControlPanel == null) { initializeExecButtonControlPanel(); } } private void updateExecCmdValue() { execCmd = execButtonModel.getData().getExecCmd(); String cmdLine = "Exec Cmd: " + execCmd; baseDisplayName = component.getDisplayName(); execButton.setText(baseDisplayName); execButton.setToolTipText(cmdLine); execButton.setActionCommand(execCmd); } public void buttonPressed() { execCmd = execButtonModel.getData().getExecCmd(); if (execCmd == null) { String msg = "Button execute command is null."; logger.error(msg); ADVISORY_LOGGER.error(msg); } if (execCmd.endsWith("&")) { execCmd = execCmd.replace("&", ""); } List<String> commandList = new ArrayList<String>(); commandList.add(execCmd); CmdProcessBuilder cmdProcessBuilder = new CmdProcessBuilder(); if (cmdProcessBuilder.execMultipleCommands("", commandList)) { String successMsg = bundle.getString("ExecButtonSuccessMsg"); successMsg += "Execution Message: " + cmdProcessBuilder.getExecSuccessfulMsg(); ADVISORY_LOGGER.info(successMsg); } else { String errorMsg = bundle.getString("ExecButtonFailedMsg"); errorMsg += "Error Message: " + cmdProcessBuilder.getExecFailedMsg(); ADVISORY_LOGGER.error(errorMsg); } } @Override public void updateMonitoredGUI() { updateExecCmdValue(); buildFromSettings(); } @Override public void updateMonitoredGUI(PropertyChangeEvent evt) { updateExecCmdValue(); buildFromSettings(); } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_view_ExecutableButtonManifestation.java
1,869
execButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { buttonPressed(); } });
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executable_buttons_view_ExecutableButtonManifestation.java
1,870
public class TestExecutableButtonComponentProvider { private ExecutableButtonComponentProvider provider; @Mock RoleService roleService; @Mock User user; @Mock Platform mockPlatform; @BeforeMethod public void testSetup() { provider = new ExecutableButtonComponentProvider(); MockitoAnnotations.initMocks(this); (new PlatformAccess()).setPlatform(mockPlatform); Mockito.when(mockPlatform.getCurrentUser()).thenReturn(user); provider.setRoleService(roleService); } @AfterMethod public void tearDown() { provider.releaseRoleService(roleService); } @Test public void testComponentTypes() { Mockito.when(roleService.hasRole(Mockito.any(User.class), Mockito.anyString())).thenReturn(false); Assert.assertEquals(provider.getComponentTypes().iterator().next().getComponentClass(), ExecutableButtonComponent.class); Assert.assertFalse(provider.getComponentTypes().iterator().next().isCreatable()); Assert.assertEquals(provider.getComponentTypes().size(), 1); } @Test public void testComponentCreation() { Mockito.when(roleService.hasRole(Mockito.any(User.class), Mockito.eq("GA"))).thenReturn(true); Mockito.when(roleService.hasRole(Mockito.any(User.class), Mockito.eq("DTR"))).thenReturn(true); provider.setRoleService(roleService); Assert.assertEquals(provider.getComponentTypes().iterator().next().getComponentClass(), ExecutableButtonComponent.class); Assert.assertTrue(provider.getComponentTypes().iterator().next().isCreatable()); Assert.assertEquals(provider.getComponentTypes().size(), 1); } @Test public void testViews() { Assert.assertEquals(provider.getViews(ExecutableButtonComponent.class.getName()).size(), 2); Assert.assertTrue(provider.getViews("abc").isEmpty()); } @Test public void testMenuItemInfos() { Collection<MenuItemInfo> menuItems = provider.getMenuItemInfos(); Assert.assertEquals(menuItems.size(), 2); Assert.assertEquals(menuItems.iterator().next().getActionClass(), ExecutableButtonAction.class); } @Test public void testPolicyInfos() { Assert.assertTrue(provider.getPolicyInfos().size() > 0); } }
false
executableButtons_src_test_java_gov_nasa_jsc_mct_executables_buttons_TestExecutableButtonComponentProvider.java
1,871
@SuppressWarnings("serial") public class ExecutableButtonAction extends ContextAwareAction { private static final Logger logger = LoggerFactory.getLogger(ExecutableButtonAction.class); private static final Logger ADVISORY_LOGGER = LoggerFactory.getLogger("gov.nasa.jsc.advisory.service"); private static final String WINDOWS_NOT_SUPPORTED_MSG = "Windows OS platform is currently not supported yet for Executable Buttons feature."; private static final ResourceBundle bundle = ResourceBundle.getBundle("ResourceBundle"); private ActionContext currentContext; private View manifestation; private String execCmd; public ExecutableButtonAction() { super(bundle.getString("ExecButtonActionLabel")); } @Override public boolean canHandle(ActionContext context) { currentContext = context; if ( (manifestation == null) && currentContext.getSelectedManifestations().iterator().hasNext()) { manifestation = currentContext.getSelectedManifestations().iterator().next(); } return (context.getSelectedManifestations().size() == 1) && isExecutableButtonComponent(context.getSelectedManifestations().iterator().next().getManifestedComponent()); } @Override public boolean isEnabled() { manifestation = currentContext.getSelectedManifestations().iterator().next(); if (isWindows()) { logger.error(WINDOWS_NOT_SUPPORTED_MSG); OptionBox.showMessageDialog(manifestation, WINDOWS_NOT_SUPPORTED_MSG, bundle.getString("ExecButtonFailedMsg"), JOptionPane.ERROR_MESSAGE); return false; } // Executable Buttons enabled only for MacOS X and UNIX/Linux OS platforms for now. return (isExecutableButtonComponent(manifestation.getManifestedComponent()) && (isMac() || isUnixLinux())); } @Override public void actionPerformed(ActionEvent e) { if ( (manifestation == null) && currentContext.getSelectedManifestations().iterator().hasNext()) { manifestation = currentContext.getSelectedManifestations().iterator().next(); } ExecutableButtonModel execButtonModel = ExecutableButtonComponent.class.cast(manifestation.getManifestedComponent()).getModel(); execCmd = execButtonModel.getData().getExecCmd(); if (execCmd == null) { String msg = "Button execute command is null."; ADVISORY_LOGGER.error(msg); } if (execCmd.endsWith("&")) { execCmd = execCmd.replace("&", ""); } List<String> commandList = new ArrayList<String>(); commandList.add(execCmd); CmdProcessBuilder cmdProcessBuilder = new CmdProcessBuilder(); if (cmdProcessBuilder.execMultipleCommands("", commandList)) { String successMsg = bundle.getString("ExecButtonSuccessMsg"); successMsg += "\n\nExecution Message:\n" + cmdProcessBuilder.getExecSuccessfulMsg(); ADVISORY_LOGGER.info(successMsg); } else { String errorMsg = bundle.getString("ExecButtonFailedMsg"); errorMsg += "\n\nError Message:\n" + cmdProcessBuilder.getExecFailedMsg(); ADVISORY_LOGGER.error(errorMsg); } } // Windows OS platform protected static boolean isWindows() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("win") >= 0); } // MacOS platform protected static boolean isMac() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("mac") >= 0); } // UNIX/Linux platform protected static boolean isUnixLinux() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0); } private boolean isExecutableButtonComponent(AbstractComponent component) { return component.getComponentTypeID().equals(ExecutableButtonComponent.class.getName()); } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executables_buttons_actions_ExecutableButtonAction.java
1,872
@SuppressWarnings("serial") public class ExecutableButtonThisAction extends ContextAwareAction { private static final Logger logger = LoggerFactory.getLogger(ExecutableButtonThisAction.class); private static final Logger ADVISORY_LOGGER = LoggerFactory.getLogger("gov.nasa.jsc.advisory.service"); private static final String WINDOWS_NOT_SUPPORTED_MSG = "Windows OS platform is currently not supported yet for Executable Buttons feature."; private static final ResourceBundle bundle = ResourceBundle.getBundle("ResourceBundle"); private ActionContext currentContext; private View manifestation; private String execCmd; public ExecutableButtonThisAction() { super(bundle.getString("ExecButtonActionLabel")); } @Override public boolean canHandle(ActionContext context) { currentContext = context; manifestation = currentContext.getWindowManifestation(); if (isWindows()) { return false; } return isExecutableButtonComponent(manifestation.getManifestedComponent()); } @Override public boolean isEnabled() { return true; } @Override public void actionPerformed(ActionEvent e) { manifestation = currentContext.getWindowManifestation(); ExecutableButtonModel execButtonModel = ExecutableButtonComponent.class.cast(manifestation.getManifestedComponent()).getModel(); execCmd = execButtonModel.getData().getExecCmd(); if (execCmd == null) { String msg = "Button execute command is null."; ADVISORY_LOGGER.error(msg); } if (execCmd.endsWith("&")) { execCmd = execCmd.replace("&", ""); } List<String> commandList = new ArrayList<String>(); commandList.add(execCmd); CmdProcessBuilder cmdProcessBuilder = new CmdProcessBuilder(); if (cmdProcessBuilder.execMultipleCommands("", commandList)) { String successMsg = bundle.getString("ExecButtonSuccessMsg"); successMsg += "\n\nExecution Message:\n" + cmdProcessBuilder.getExecSuccessfulMsg(); ADVISORY_LOGGER.info(successMsg); } else { String errorMsg = bundle.getString("ExecButtonFailedMsg"); errorMsg += "\n\nError Message:\n" + cmdProcessBuilder.getExecFailedMsg(); ADVISORY_LOGGER.error(errorMsg); } } // Windows OS platform protected static boolean isWindows() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("win") >= 0); } // MacOS platform protected static boolean isMac() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("mac") >= 0); } // UNIX/Linux platform protected static boolean isUnixLinux() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0); } private boolean isExecutableButtonComponent(AbstractComponent component) { return component.getComponentTypeID().equals(ExecutableButtonComponent.class.getName()); } }
false
executableButtons_src_main_java_gov_nasa_jsc_mct_executables_buttons_actions_ExecutableButtonThisAction.java
1,873
public class TestExecutableButtonAction { private ExecutableButtonAction executableButtonAction; @Mock private View manifestation; @Mock private AbstractComponent abstractComp; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); executableButtonAction = new ExecutableButtonAction(); } private final ActionContext mockActionContextObject() { ActionContext context = new ActionContext() { @Override public View getWindowManifestation() { return View.NULL_VIEW_MANIFESTATION; } @Override public Collection<View> getSelectedManifestations() { return Collections.singleton(manifestation); } @Override public Collection<View> getRootManifestations() { return Collections.emptySet(); } }; return context; } @Test public void testCanHandle() { ActionContext context = mockActionContextObject(); Assert.assertTrue(context.getSelectedManifestations().size() == 1); Assert.assertNotNull(context); Mockito.when(manifestation.getManifestedComponent()).thenReturn(abstractComp); Assert.assertNotNull(abstractComp); } @Test public void testIsEnabled() { Assert.assertNotNull(executableButtonAction); } }
false
executableButtons_src_test_java_gov_nasa_jsc_mct_executables_buttons_actions_TestExecutableButtonAction.java
1,874
ActionContext context = new ActionContext() { @Override public View getWindowManifestation() { return View.NULL_VIEW_MANIFESTATION; } @Override public Collection<View> getSelectedManifestations() { return Collections.singleton(manifestation); } @Override public Collection<View> getRootManifestations() { return Collections.emptySet(); } };
false
executableButtons_src_test_java_gov_nasa_jsc_mct_executables_buttons_actions_TestExecutableButtonAction.java
1,875
public class ExampleActivator implements BundleActivator { //private static final Logger logger = LoggerFactory.getLogger(ExampleActivator.class); @Override public void start(BundleContext context) { //logger.info("starting bundle {0}", context.getBundle().getSymbolicName()); //ServiceReference sr = context.getServiceReference(FeedAggregator.class.getName()); //Object o = context.getService(sr); } @Override public void stop(BundleContext context) { //logger.info("stopping bundle {0}", context.getBundle().getSymbolicName()); } }
false
exampleplugin_src_main_java_org_acme_example_ExampleActivator.java
1,876
@SuppressWarnings("serial") public class APICreationAction extends ContextAwareAction { private static final AtomicInteger newCount = new AtomicInteger(); private static ResourceBundle bundle = ResourceBundle.getBundle("ExampleResourceBundle"); //NO18N /** * The currently selected manifestations. This will be either the actually selected manifestations or the * component for the window if nothing is selected. */ private Collection<View> selectedManifestations; public APICreationAction() { super(bundle.getString("ProgrammaticCreate")); //NO18N } @Override public void actionPerformed(ActionEvent e) { // add a new example component to each component currently selected for (View manifestation : selectedManifestations) { AbstractComponent component = manifestation.getManifestedComponent(); createChildInstance(component); } } /** * Adds a new instance of an ExampleComponent as a child instance of the component using the * <code>ComponentRegistry</code> APIs. * @param component to add child example component to. This component will be editable as this * has already been checked in the isEnable method. */ private void createChildInstance(AbstractComponent component) { // acquire the ComponentRegistry through the access object. The ComponentRegistry // will be injected through the OSGi declarative services model ComponentRegistry registry = ComponentRegistryAccess.getComponentRegistry(); if (registry != null) { // use the ComponentRegistry service to create a new instance of a component ExampleComponent ec = registry.newInstance(ExampleComponent.class, component); // additional information can be collected here to populate a model. This simply // sets a unique name ec.setDisplayName("newComponentFromMenu"+newCount.incrementAndGet()); // show the newly created component in it's own window ec.open(); } } /** * Determines if the component is an instance of ExampleComponent. * @param component to match against the ExampleComponent type * @return true if an ExampleComponent is provided false otherwise */ private boolean isExampleComponent(AbstractComponent component) { return component instanceof ExampleComponent; } @Override public boolean canHandle(ActionContext context) { // set the set of manifestations to be either the selected manifestations or the manifestation of the window selectedManifestations = context.getSelectedManifestations(); if (selectedManifestations.isEmpty()) { selectedManifestations = Collections.singletonList(context.getWindowManifestation()); } // only show the action if all the selected components are Example Components for (View manifestation : selectedManifestations) { AbstractComponent component = manifestation.getManifestedComponent(); if (!(isExampleComponent(component))) { return false; } } return true; } @Override public boolean isEnabled() { return true; } }
false
exampleplugin_src_main_java_org_acme_example_actions_APICreationAction.java
1,877
@SuppressWarnings("serial") public class AboutExampleAction extends ContextAwareAction { private static ResourceBundle bundle = ResourceBundle.getBundle("ExampleResourceBundle"); //NO18N public AboutExampleAction() { super(bundle.getString("about_text")); //NO18N } @Override public void actionPerformed(ActionEvent e) { OptionBox.showMessageDialog((Component) e.getSource(), bundle.getString("about_message")); //NO18N } @Override public boolean canHandle(ActionContext context) { return true; } @Override public boolean isEnabled() { return true; } }
false
exampleplugin_src_main_java_org_acme_example_actions_AboutExampleAction.java
1,878
@SuppressWarnings("serial") public class AddOrRemoveNodeBorderAction extends GroupAction { private static ResourceBundle bundle = ResourceBundle.getBundle("ExampleResourceBundle"); public AddOrRemoveNodeBorderAction() { this(bundle.getString("AddOrRemoveNodeBorderText")); } protected AddOrRemoveNodeBorderAction(String name) { super(name); } @Override public void actionPerformed(ActionEvent e) { } @Override public boolean canHandle(ActionContext context) { Collection<View> selectedManifestations = context.getSelectedManifestations(); if (selectedManifestations.size() != 1) return false; View manifestation = selectedManifestations.iterator().next(); if (!(manifestation.getManifestedComponent() instanceof ExampleComponent)) return false; RadioAction[] radioActions = { new AddLineBorder(manifestation), new RemoveLineBorder(manifestation) }; setActions(radioActions); return true; } @Override public boolean isEnabled() { return false; } private class AddLineBorder extends RadioAction { private View manifestation; public AddLineBorder(View manifestation) { this.manifestation = manifestation; putValue(Action.NAME, "Turn On Border"); putValue(Action.SHORT_DESCRIPTION, "The border will not be persisted for the next MCT session."); } @Override public boolean isMixed() { return false; } @Override public boolean isSelected() { Border border = manifestation.getBorder(); return border instanceof LineBorder; } @Override public void actionPerformed(ActionEvent e) { manifestation.setBorder(BorderFactory.createLineBorder(Color.red, 3)); } } private class RemoveLineBorder extends RadioAction { private View manifestation; public RemoveLineBorder(View manifestation) { this.manifestation = manifestation; putValue(Action.NAME, "Turn Off Border"); } @Override public boolean isMixed() { return false; } @Override public boolean isSelected() { Border border = manifestation.getBorder(); return border == null; } @Override public void actionPerformed(ActionEvent e) { manifestation.setBorder(null); } } }
false
exampleplugin_src_main_java_org_acme_example_actions_AddOrRemoveNodeBorderAction.java
1,879
private class AddLineBorder extends RadioAction { private View manifestation; public AddLineBorder(View manifestation) { this.manifestation = manifestation; putValue(Action.NAME, "Turn On Border"); putValue(Action.SHORT_DESCRIPTION, "The border will not be persisted for the next MCT session."); } @Override public boolean isMixed() { return false; } @Override public boolean isSelected() { Border border = manifestation.getBorder(); return border instanceof LineBorder; } @Override public void actionPerformed(ActionEvent e) { manifestation.setBorder(BorderFactory.createLineBorder(Color.red, 3)); } }
false
exampleplugin_src_main_java_org_acme_example_actions_AddOrRemoveNodeBorderAction.java
1,880
private class RemoveLineBorder extends RadioAction { private View manifestation; public RemoveLineBorder(View manifestation) { this.manifestation = manifestation; putValue(Action.NAME, "Turn Off Border"); } @Override public boolean isMixed() { return false; } @Override public boolean isSelected() { Border border = manifestation.getBorder(); return border == null; } @Override public void actionPerformed(ActionEvent e) { manifestation.setBorder(null); } }
false
exampleplugin_src_main_java_org_acme_example_actions_AddOrRemoveNodeBorderAction.java
1,881
@SuppressWarnings("serial") public class BeepAction extends ContextAwareAction { public BeepAction() { super("Beep"); } @Override public void actionPerformed(ActionEvent e) { Toolkit.getDefaultToolkit().beep(); } @Override public boolean canHandle(ActionContext context) { return true; } @Override public boolean isEnabled() { return true; } }
false
exampleplugin_src_main_java_org_acme_example_actions_BeepAction.java
1,882
@SuppressWarnings("serial") public class SubmenuMenu extends ContextAwareMenu { private static final String OBJECTS_SUBMENU_EXT = "objects/submenu.ext"; public SubmenuMenu() { super("Example Submenu"); } @Override protected void populate() { Collection<MenuItemInfo> infos = new ArrayList<MenuItemInfo>(); infos.add(new MenuItemInfo("OBJECTS_SUBMENU_BEEP", MenuItemType.NORMAL)); addMenuItemInfos(OBJECTS_SUBMENU_EXT, infos); } @Override public boolean canHandle(ActionContext context) { Collection<View> selectedManifestations = context.getSelectedManifestations(); if (selectedManifestations.size() != 1) return false; return selectedManifestations.iterator().next().getManifestedComponent() instanceof ExampleComponent; } }
false
exampleplugin_src_main_java_org_acme_example_actions_SubmenuMenu.java
1,883
public final class BooleanPropertyEditor implements PropertyEditor<Object> { ExampleComponent exampleComponent = null; public BooleanPropertyEditor(AbstractComponent component) { exampleComponent = (ExampleComponent)component; } @Override public String getAsText() { throw new UnsupportedOperationException(); } @Override public void setAsText(String newValue) throws IllegalArgumentException { throw new UnsupportedOperationException(); } @Override public Boolean getValue() { return exampleComponent.getModel().getData().isVerified(); } @Override public void setValue(Object selection) { exampleComponent.getModel().getData().setVerified((Boolean) selection); } @Override public List<Object> getTags() { throw new UnsupportedOperationException(); } }
false
exampleplugin_src_main_java_org_acme_example_component_BooleanPropertyEditor.java
1,884
public class ComponentRegistryAccess { private static AtomicReference<ComponentRegistry> registry = new AtomicReference<ComponentRegistry>(); // this is not a traditional singleton as this class is created by the OSGi declarative services mechanism. /** * Returns the component registry instance. This will not return null as the cardinality of * the component specified through the OSGi components services is 1. * @return a component registry service instance */ public static ComponentRegistry getComponentRegistry() { return registry.get(); } /** * set the active instance of the <code>ComponentRegistry</code>. This method is invoked by * OSGi (see the OSGI-INF/component.xml file for additional details). * @param componentRegistry available in MCT */ public void setRegistry(ComponentRegistry componentRegistry) { registry.set(componentRegistry); } /** * release the active instance of the <code>ComponentRegistry</code>. This method is invoked by * OSGi (see the OSGI-INF/component.xml file for additional details). * @param componentRegistry to be released */ public void releaseRegistry(ComponentRegistry componentRegistry) { registry.set(null); } }
false
exampleplugin_src_main_java_org_acme_example_component_ComponentRegistryAccess.java
1,885
public final class EnumerationPropertyEditor implements PropertyEditor<String> { ExampleComponent exampleComponent = null; public EnumerationPropertyEditor(AbstractComponent component) { exampleComponent = (ExampleComponent)component; } @Override public String getAsText() { throw new UnsupportedOperationException(); } @Override public void setAsText(String newValue) throws IllegalArgumentException { throw new UnsupportedOperationException(); } @Override public String getValue() { return exampleComponent.getModel().getData().getGenderSelection(); } @Override public void setValue(Object selection) { exampleComponent.getModel().getData().setGenderSelection((String) selection); } @Override public List<String> getTags() { return Arrays.asList(exampleComponent.getModel().getData().gender); } }
false
exampleplugin_src_main_java_org_acme_example_component_EnumerationPropertyEditor.java
1,886
public class ExampleComponent extends AbstractComponent { private final AtomicReference<ExampleModelRole> model = new AtomicReference<ExampleModelRole>(new ExampleModelRole()); @Override protected <T> T handleGetCapability(Class<T> capability) { if (ModelStatePersistence.class.isAssignableFrom(capability)) { JAXBModelStatePersistence<ExampleModelRole> persistence = new JAXBModelStatePersistence<ExampleModelRole>() { @Override protected ExampleModelRole getStateToPersist() { return model.get(); } @Override protected void setPersistentState(ExampleModelRole modelState) { model.set(modelState); } @Override protected Class<ExampleModelRole> getJAXBClass() { return ExampleModelRole.class; } }; return capability.cast(persistence); } return null; } public ExampleModelRole getModel() { return model.get(); } @Override public List<PropertyDescriptor> getFieldDescriptors() { // Provide an ordered list of fields to be included in the MCT Platform's InfoView. List<PropertyDescriptor> fields = new ArrayList<PropertyDescriptor>(); // Describe the field "dataDescription" in the business class MyData. // Here we specify an immutable field, whereby its initial value is specified using a convenience class TextInitializer. String labelText = "World Swimming Event"; PropertyDescriptor swimmingEvent = new PropertyDescriptor(labelText, new TextInitializer(getModel().getData().getDataDescription()), VisualControlDescriptor.Label); // Describe MyData's field "doubleData". // We specify a mutable text field. The control display's values are maintained in the business model // via the PropertyEditor object. When a new value is to be set, the editor also validates the prospective value. PropertyDescriptor swimmingWorldRecord = new PropertyDescriptor("Men's World Record (Rome 2009 Phelps)", new TextPropertyEditor(this), VisualControlDescriptor.TextField); swimmingWorldRecord.setFieldMutable(true); // Describe MyData's field "genderSelection". Here is a mutabl combo box visual control. The control's initial value, // and its selection states are taken from the business model via the PropertyEditor. PropertyDescriptor gender = new PropertyDescriptor("Gender", new EnumerationPropertyEditor(this), VisualControlDescriptor.ComboBox); gender.setFieldMutable(true); // Describe MyData's field "verified". This is a mutable check box visual control. PropertyDescriptor verified = new PropertyDescriptor("Verified", new BooleanPropertyEditor(this), VisualControlDescriptor.CheckBox); verified.setFieldMutable(true); fields.add(swimmingEvent); fields.add(swimmingWorldRecord); fields.add(gender); fields.add(verified); return fields; } }
false
exampleplugin_src_main_java_org_acme_example_component_ExampleComponent.java
1,887
JAXBModelStatePersistence<ExampleModelRole> persistence = new JAXBModelStatePersistence<ExampleModelRole>() { @Override protected ExampleModelRole getStateToPersist() { return model.get(); } @Override protected void setPersistentState(ExampleModelRole modelState) { model.set(modelState); } @Override protected Class<ExampleModelRole> getJAXBClass() { return ExampleModelRole.class; } };
false
exampleplugin_src_main_java_org_acme_example_component_ExampleComponent.java
1,888
public class ExampleComponentProvider extends AbstractComponentProvider { // use a resource bundle for strings to enable localization in the future if required private static ResourceBundle bundle = ResourceBundle.getBundle("ExampleResourceBundle"); private final ComponentTypeInfo exampleComponentType; private final ComponentTypeInfo telemetryComponentType; public ExampleComponentProvider() { // this is the component type we are providing. The display name and description are used // by the MCT menu system for creating new instances and thus should be human readable // and descriptive exampleComponentType = new ComponentTypeInfo( bundle.getString("display_name"), bundle.getString("description"), ExampleComponent.class); telemetryComponentType = new ComponentTypeInfo( bundle.getString("telemetry_display_name"), bundle.getString("telemetry_description"), TelemetryComponent.class); } @Override public Collection<ComponentTypeInfo> getComponentTypes() { // return the component types provided return Arrays.asList(exampleComponentType, telemetryComponentType); } @Override public Collection<ViewInfo> getViews(String componentTypeId) { // return a view if desired for the components being created. Note that this method is called // for every component type so a view could be supplied for any component type not just // components supplied by this provider. // Also, note that the default node view, canvas view, and housing view will be supplied // by the MCT platform. if (componentTypeId.equals(ExampleComponent.class.getName())) { return Arrays.asList( new ViewInfo(CenterPanePanel.class, bundle.getString("CenterPaneViewName"), ViewType.CENTER), new ViewInfo(CenterPanePanel.class, bundle.getString("CenterPaneViewName"), ViewType.OBJECT), new ViewInfo(PublicInfoView.class, bundle.getString("PublicViewName"), ViewType.OBJECT), new ViewInfo(PrivateInfoView.class, bundle.getString("PrivateViewName"), ViewType.OBJECT), new ViewInfo(SaveModelStateView.class, bundle.getString("SaveModelStateViewName"), ViewType.OBJECT), new ViewInfo(ShowChildrenInTableView.class, bundle.getString("ShowChildrenInTableViewName"), ViewType.OBJECT) ); } return Collections.emptyList(); } @Override public Collection<MenuItemInfo> getMenuItemInfos() { return Arrays.asList( // Additional menu items can be added to the following // menus with the corresponding menubarPaths: // This => /this/additions // Objects => /objects/additions // Help => /help/additions // add menu items to help -- this will show up as a help topic for the example plugin new MenuItemInfo( "/help/additions", // NOI18N "ABOUT_EXAMPLE_ACTION", //NO18N MenuItemType.NORMAL, AboutExampleAction.class), // add menu item to the objects menu -- this will demonstrate programmatic creation for ExampleComponents new MenuItemInfo( "/objects/additions", // NOI18N "API_CREATION_ACTION", //NO18N MenuItemType.NORMAL, APICreationAction.class), // add menu item to the objects menu -- this will be inline as a radio button group under the objects menu new MenuItemInfo( "/objects/additions", //NOI18N "CHANGE_COLOR_ACTION", //NOI18N MenuItemType.RADIO_GROUP, AddOrRemoveNodeBorderAction.class), new MenuItemInfo( "/objects/additions", //NOI18N "SUBMENU", //NOI18N SubmenuMenu.class), new MenuItemInfo( "objects/submenu.ext", //NOI18N "OBJECTS_SUBMENU_BEEP", //NOI18N MenuItemType.NORMAL, BeepAction.class)); } @Override public Collection<PolicyInfo> getPolicyInfos() { /* * Here is an example of registering a policy to a platform provided * policy category. Platform-provided policy categories are defined * in PolicyInfo.CatetoryType, which is an enum. * A new category can also be added by passing in a unique String to * the category name in PolicyInfo constructor. */ return Collections.singletonList( new PolicyInfo(PolicyInfo.CategoryType.FILTER_VIEW_ROLE.getKey(), FilterViewPolicy.class)); /* * External plugins can execute a policy category by accessing the * PolicyManager, which is available as an OSGi service. * * To access the PolicyManager, a class PolicyManagerAccess should be created. * This class is used to inject an instance of the PolicyManager using declarative * services (see OSGI-INF/component.xml for examples for ComponentRegistryAccess). * * The following code snippet shows how to execute a policy category: * * PolicyManager policyManager = PolicyManagerAccess.getPolicyManager(); * PolicyContext context = new PolicyContext(); * context.setProperty(String key, Object value); * ... * ... maybe more properties to be set * ... * ExecutionResult result = * policyManager.execute(String categoryKey, PolicyContext context); */ } }
false
exampleplugin_src_main_java_org_acme_example_component_ExampleComponentProvider.java
1,889
@XmlRootElement() @XmlAccessorType(XmlAccessType.FIELD) public class ExampleModelRole { // This is the model data. // You can choose whether or not your model data will be persisted using setPersistable(). // // In this example, we will persist data by setting persistable to true, and annotating our model role. // The View Model Role associated with this component allows a user to modify and save the data. When the user commits the // change, MCT persists model data using JAXB. The XML text written to the MCT database is similar to // <exampleModelRole><data><doubleData>46.91</doubleData><dataDescription>100 free</dataDescription></data></exampleModelRole> private MyData data = new MyData (); public MyData getData() { return data; } }
false
exampleplugin_src_main_java_org_acme_example_component_ExampleModelRole.java
1,890
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class MyData { private double doubleData = 49.82; //seconds private String dataDescription = "100m fly"; // World record men 100m fly (Rome 2009) Phelps final String[] gender = {"men", "women"}; private String genderSelection = gender[1]; private boolean verified = false; public double getDoubleData() { return doubleData; } public void setDoubleData(double data) { this.doubleData = data; } public String getDataDescription() { return dataDescription; } public void setDataDescription(String dataDescription) { this.dataDescription = dataDescription; } public String[] getGender() { return gender; } public String getGenderSelection() { return genderSelection; } public void setGenderSelection(String genderSelection) { this.genderSelection = genderSelection; } public boolean isVerified() { return verified; } public void setVerified(boolean verified) { this.verified = verified; } }
false
exampleplugin_src_main_java_org_acme_example_component_MyData.java
1,891
public final class TextPropertyEditor implements PropertyEditor<Object> { ExampleComponent exampleComponent = null; public TextPropertyEditor(AbstractComponent component) { exampleComponent = (ExampleComponent)component; } @Override public String getAsText() { double numericData = exampleComponent.getModel().getData().getDoubleData(); return String.valueOf(numericData); } /** * Set and save the value in the business model. * * @param newValue the new value * @throws exception if the new value is invalid. MCT platform will handle this exception and * disallow the prospective edit. */ @Override public void setAsText(String newValue) throws IllegalArgumentException { String result = verify(newValue); if (verify(newValue) != null) { throw new IllegalArgumentException(result); } MyData businessModel = exampleComponent.getModel().getData(); double d = Double.parseDouble(newValue); // verify() took care of a possible number format exception businessModel.setDoubleData(d); } private String verify(String s) { assert s != null; if (s.isEmpty()) { return "Cannot be unspecified"; } try { Double.parseDouble(s); } catch (NumberFormatException e) { return "Must be a numeric"; } return null; } @Override public String getValue() { throw new UnsupportedOperationException(); } @Override public void setValue(Object selection) { throw new UnsupportedOperationException(); } @Override public List<Object> getTags() { throw new UnsupportedOperationException(); } }
false
exampleplugin_src_main_java_org_acme_example_component_TextPropertyEditor.java
1,892
public class FilterViewPolicy implements Policy { @Override public ExecutionResult execute(PolicyContext context) { ExecutionResult trueResult = new ExecutionResult(context, true, ""); if (!checkArguments(context)) return trueResult; // Return true to skip this policy and pass the context to the next one. ExampleComponent targetComponent = context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), ExampleComponent.class); ViewInfo viewInfo = context.getProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), ViewInfo.class); if (viewInfo.getViewClass().equals(PublicInfoView.class)) return new ExecutionResult(context, false, targetComponent.getDisplayName() + " is private, cannot show " + viewInfo.getClass().getName()); //NOI18N if (viewInfo.getViewClass().equals(PrivateInfoView.class)) return new ExecutionResult(context, false, targetComponent.getDisplayName() + " is public, cannot show " + viewInfo.getClass().getName()); //NOI18N return trueResult; } /** * This a utility method that checks if <code>context</code> * contains the correct set of arguments to process this policy. * @param context the <code>PolicyContext</code> * @return true if the <code>context</code> contains the correct arguments; otherwise return false */ private boolean checkArguments(PolicyContext context) { if (context.getProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), ExampleComponent.class) == null) return false; // Filtering only InspectableViewRole types return !(context.getProperty(PolicyContext.PropertyName.VIEW_TYPE.getName(), ViewType.class) != ViewType.OBJECT); } }
false
exampleplugin_src_main_java_org_acme_example_policy_FilterViewPolicy.java
1,893
public class ExampleDataProvider implements DataProvider { private Map<String, TestDataFeed> feeds = new ConcurrentHashMap<String, TestDataFeed>(); @Override public Map<String, SortedMap<Long, Map<String, String>>> getData(Set<String> feedIDs, long startTime, long endTime, TimeUnit timeUnit) { Map<String, SortedMap<Long, Map<String, String>>> out = new HashMap<String, SortedMap<Long, Map<String, String>>>(); for(String feedID : feedIDs) { if (canHandleFeed(feedID)) { TestDataFeed feed = feeds.get(feedID); if(feed == null) { feed = new TestDataFeed(); feed.setPeriodInSeconds(feed.getPeriodInSeconds() * (1 + feed.hashCode() / (double) Integer.MAX_VALUE / 2)); feed.setAmplitude(feed.getAmplitude() * (1 + (feed + " ").hashCode() / (double) Integer.MAX_VALUE / 2)); feeds.put(feedID, feed); } out.put(feedID, feed.getData(startTime, endTime, timeUnit)); } } return out; } private boolean canHandleFeed(String feedId) { return feedId.startsWith(TelemetryComponent.TelemetryPrefix); } @Override public LOS getLOS() { // use the medium level of service if the data can be accessed relatively quickly (local storage) // this case is nominal as the return LOS.medium; } @Override public Map<String, List<Map<String, String>>> getData(Set<String> feedIDs, TimeUnit timeUnit, long startTime, long endTime) { Map<String, List<Map<String, String>>> out = new HashMap<String, List<Map<String, String>>>(); for(String feedID : feedIDs) { TestDataFeed feed = feeds.get(feedID); if(feed == null) { feed = new TestDataFeed(); feeds.put(feedID, feed); } out.put(feedID, new ArrayList<Map<String, String>>(feed.getData(startTime, endTime, timeUnit).values())); } return out; } @Override public boolean isFullyWithinTimeSpan(String feedID, long startTime, TimeUnit timeUnit) { // since this is the only provider for this specific type of telemetry this can always return // true. If there were multiple data providers working together this would return false // if additional data sources should be consulted. return true; } }
false
exampleplugin_src_main_java_org_acme_example_telemetry_ExampleDataProvider.java
1,894
public class TelemetryComponent extends AbstractComponent implements FeedProvider { public static final String TelemetryPrefix = "example:"; private AtomicReference<TelemetryModel> model = new AtomicReference<TelemetryModel> (new TelemetryModel()); public TelemetryComponent() { super(); } @Override public boolean isLeaf() { return true; } @Override protected <T> T handleGetCapability(Class<T> capability) { if (FeedProvider.class.isAssignableFrom(capability)) { return capability.cast(this); } if (ModelStatePersistence.class.isAssignableFrom(capability)) { JAXBModelStatePersistence<TelemetryModel> persistence = new JAXBModelStatePersistence<TelemetryModel>() { @Override protected TelemetryModel getStateToPersist() { return model.get(); } @Override protected void setPersistentState(TelemetryModel modelState) { model.set(modelState); } @Override protected Class<TelemetryModel> getJAXBClass() { return TelemetryModel.class; } }; return capability.cast(persistence); } return null; } @Override public String getLegendText() { return getDisplayName() + "\n" + getExternalKey(); } @Override public int getMaximumSampleRate() { // This should be based on metadata return 1; } @Override public String getSubscriptionId() { return TelemetryPrefix+getComponentId(); } public TelemetryModel getModel() { return model.get(); } @Override public TimeService getTimeService() { return TimeServiceImpl.getInstance(); } @Override public FeedType getFeedType() { return FeedType.FLOATING_POINT; } @Override public String getCanonicalName() { return getDisplayName(); } @Override public RenderingInfo getRenderingInfo(Map<String, String> data) { String riAsString = data.get(FeedProvider.NORMALIZED_RENDERING_INFO); RenderingInfo ri = null; assert data.get(FeedProvider.NORMALIZED_VALUE_KEY) != null : "The VALUE key is required for a valid status."; assert data.get(FeedProvider.NORMALIZED_TIME_KEY) != null : "The TIME key is required for a valid status."; ri = FeedProvider.RenderingInfo.valueOf(riAsString); return ri; } @Override public long getValidDataExtent() { return System.currentTimeMillis(); } @Override public boolean isPrediction() { return false; } @Override public boolean isNonCODDataBuffer() { // TODO Auto-generated method stub return false; } }
false
exampleplugin_src_main_java_org_acme_example_telemetry_TelemetryComponent.java
1,895
JAXBModelStatePersistence<TelemetryModel> persistence = new JAXBModelStatePersistence<TelemetryModel>() { @Override protected TelemetryModel getStateToPersist() { return model.get(); } @Override protected void setPersistentState(TelemetryModel modelState) { model.set(modelState); } @Override protected Class<TelemetryModel> getJAXBClass() { return TelemetryModel.class; } };
false
exampleplugin_src_main_java_org_acme_example_telemetry_TelemetryComponent.java
1,896
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class TelemetryData { private String telemetryId; private String telemetryDescription; public void setId(String telemetryId) { this.telemetryId = telemetryId; } public String getId() { return telemetryId; } public void setDescription(String telemetryDescription) { this.telemetryDescription = telemetryDescription; } public String getDescription() { return telemetryDescription; } }
false
exampleplugin_src_main_java_org_acme_example_telemetry_TelemetryData.java
1,897
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class TelemetryModel { // This is the model data. // You can choose whether or not your model data will be persisted using setPersistable(). // // In this example, we will persist data by setting persistable to true, and annotating our model role. // The View associated with this component allows a user to modify and save the data. When the user commits the // change, MCT persists model data using JAXB. The XML text written to the MCT database is similar to // <exampleModelRole><data><doubleData>46.91</doubleData><dataDescription>100 free</dataDescription></data></exampleModelRole> private TelemetryData data = new TelemetryData (); public TelemetryData getData() { return data; } }
false
exampleplugin_src_main_java_org_acme_example_telemetry_TelemetryModel.java
1,898
public class TestDataFeed { /** Data points per second. */ private double pointsPerSecond = 10; /** Period of the sine wave. */ private double periodInSeconds = 60; /** Amplitude of the sine wave. */ private double amplitude = 1; /** Time between each Loss Of Signal*/ private double losPeriodInSeconds = 60; /** Phase of the Loss Of Signal, relative to the base curve. */ private double losPhase = 0; /** Threshold below which data is marked as invalid. Range is -1 to 1. */ private double losThreshold = 0; private static final Color GOOD_COLOR = new Color(0, 138, 0); private static final Color LOS_COLOR = new Color(0, 72, 217); public SortedMap<Long, Map<String, String>> getData(long startTime, long endTime, TimeUnit timeUnit) { startTime=TimeUnit.MILLISECONDS.convert(startTime, timeUnit); endTime=TimeUnit.MILLISECONDS.convert(endTime, timeUnit); // Align the start and end times such that each is a multiple of the period. double pointsPerMS = pointsPerSecond / 1000; long start = (long) (Math.ceil(startTime * pointsPerMS) / pointsPerMS); long end = (long) (Math.floor(endTime * pointsPerMS) / pointsPerMS); if(start > endTime || end < startTime) { // no data in this range return new TreeMap<Long, Map<String, String>>(); } // Generate the data points in the given range. SortedMap<Long, Map<String, String>> data = new TreeMap<Long, Map<String, String>>(); double time = start; while(time <= end) { double value = amplitude * Math.sin(time * 2 * Math.PI / periodInSeconds / 1000); boolean valid = Math.sin(time * 2 * Math.PI / losPeriodInSeconds / 1000 + losPhase) < losThreshold; Map<String, String> datum = new HashMap<String, String>(); datum.put(FeedProvider.NORMALIZED_IS_VALID_KEY, Boolean.toString(valid)); String status = valid ? " ":"S"; Color c = valid ? GOOD_COLOR : LOS_COLOR; RenderingInfo ri = new RenderingInfo( Double.toString(value), c, status, c, valid ); ri.setPlottable(valid); datum.put(FeedProvider.NORMALIZED_RENDERING_INFO, ri.toString()); datum.put(FeedProvider.NORMALIZED_TIME_KEY, Long.toString((long) time)); datum.put(FeedProvider.NORMALIZED_VALUE_KEY, Double.toString(value)); datum.put(FeedProvider.NORMALIZED_TELEMETRY_STATUS_CLASS_KEY, "1"); data.put((long) time, datum); time = Math.ceil((time + 1) * pointsPerMS) / pointsPerMS; } return data; } /** * Sets the period of the sine wave. * @param periodInSeconds period of the sine wave, in seconds */ public void setPeriodInSeconds(double periodInSeconds) { this.periodInSeconds = periodInSeconds; } /** * Returns the period of the sine wave. * @return period of the sine wave, in seconds */ public double getPeriodInSeconds() { return periodInSeconds; } /** * Returns the amplitude of the sine wave. * @return amplitude of the sine wave */ public double getAmplitude() { return amplitude; } /** * Sets the amplitude of the sine wave. * @param amplitude amplitude of the sine wave */ public void setAmplitude(double amplitude) { this.amplitude = amplitude; } }
false
exampleplugin_src_main_java_org_acme_example_telemetry_TestDataFeed.java
1,899
public class TimeServiceImpl extends TimeService { private static final TimeServiceImpl timeService = new TimeServiceImpl(); public static TimeServiceImpl getInstance(){ return timeService; } private TimeServiceImpl() {} @Override public long getCurrentTime() { return System.currentTimeMillis(); } }
false
exampleplugin_src_main_java_org_acme_example_telemetry_TimeServiceImpl.java