/** * Formats a message with the specified arguments using the given locale information. * * @param locale The locale of the message. * @param key The message key. * @param arguments The message replacement text arguments. The order of the arguments must match * that of the placeholders in the actual message. * @return Returns the formatted message. * @throws MissingResourceException Thrown if the message with the specified key cannot be found. */ public String formatMessage(Locale locale, String key, Object[] arguments) throws MissingResourceException { if (fResourceBundle == null || locale != fLocale) { if (locale != null) { fResourceBundle = PropertyResourceBundle.getBundle("org.apache.xerces.impl.msg.XIncludeMessages", locale); // memorize the most-recent locale fLocale = locale; } if (fResourceBundle == null) fResourceBundle = PropertyResourceBundle.getBundle("org.apache.xerces.impl.msg.XIncludeMessages"); } String msg = fResourceBundle.getString(key); if (arguments != null) { try { msg = java.text.MessageFormat.format(msg, arguments); } catch (Exception e) { msg = fResourceBundle.getString("FormatFailed"); msg += " " + fResourceBundle.getString(key); } } if (msg == null) { msg = fResourceBundle.getString("BadMessageKey"); throw new MissingResourceException(msg, "org.apache.xerces.impl.msg.XIncludeMessages", key); } return msg; }
/** * Formats a message with the specified arguments using the given locale information. * * @param locale The locale of the message. * @param key The message key. * @param arguments The message replacement text arguments. The order of the arguments must match * that of the placeholders in the actual message. * @return Returns the formatted message. * @throws MissingResourceException Thrown if the message with the specified key cannot be found. */ public String formatMessage(Locale locale, String key, Object[] arguments) throws MissingResourceException { if (fResourceBundle == null || locale != fLocale) { if (locale != null) { fResourceBundle = PropertyResourceBundle.getBundle( "com.sun.org.apache.xerces.internal.impl.msg.XMLMessages", locale); // memorize the most-recent locale fLocale = locale; } if (fResourceBundle == null) fResourceBundle = PropertyResourceBundle.getBundle( "com.sun.org.apache.xerces.internal.impl.msg.XMLMessages"); } // format message String msg; try { msg = fResourceBundle.getString(key); if (arguments != null) { try { msg = java.text.MessageFormat.format(msg, arguments); } catch (Exception e) { msg = fResourceBundle.getString("FormatFailed"); msg += " " + fResourceBundle.getString(key); } } } // error catch (MissingResourceException e) { msg = fResourceBundle.getString("BadMessageKey"); throw new MissingResourceException(key, msg, key); } // no message if (msg == null) { msg = key; if (arguments.length > 0) { StringBuffer str = new StringBuffer(msg); str.append('?'); for (int i = 0; i < arguments.length; i++) { if (i > 0) { str.append('&'); } str.append(String.valueOf(arguments[i])); } } } return msg; }
@Test public void testLoadMultipleFilesAndNoLookUps() { ResourceBundle bundle1 = PropertyResourceBundle.getBundle("propertyServiceImplTest-noLookUps-1"); ResourceBundle bundle2 = PropertyResourceBundle.getBundle("propertyServiceImplTest-noLookUps-2"); List<ResourceBundle> bundles = new ArrayList<ResourceBundle>(); bundles.add(bundle1); bundles.add(bundle2); LookUpKeyResolver resolver = new LookUpKeyResolver() { @Override public LookUpKey resolve(String lookUpKey) { return new LookUpKey(null, lookUpKey, lookUpKey); } }; PropertyServiceImpl service = new PropertyServiceImpl(resolver); Set<ClearProperty> properties = service.load(bundles); Assert.assertNotNull(properties); Assert.assertEquals(properties.size(), 5); for (ClearProperty property : properties) { String key = property.getKey(); String value = property.getValue(); String lookUp = property.getLookUpKey().getLookUp(); Assert.assertNotNull(property.getLookUpKey()); Assert.assertNotNull(property.getValue()); Assert.assertNotNull(property.getKey()); Assert.assertNull(lookUp); if (!(key.equals("foo") || key.equals("baz") || key.equals("qix") || key.equals("stux") || key.equals("flix"))) { Assert.fail("Key must either be foo, baz, or qix"); } if (!(value.equals("bar") || value.equals("waldo") || value.equals("qux") || value.equals("flux") || value.equals("glux"))) { Assert.fail("Key must either be bar, waldo, or qux"); } } }
@Test public void testFilterWithMultipleFilesAndMultipleLookUps() { String expectedLookUp1 = "lookUp1"; String expectedLookUp2 = "lookUp2"; ResourceBundle bundle1 = PropertyResourceBundle.getBundle("propertyServiceImplTest-withLookUps-1"); ResourceBundle bundle2 = PropertyResourceBundle.getBundle("propertyServiceImplTest-withLookUps-2"); List<ResourceBundle> bundles = new ArrayList<ResourceBundle>(); bundles.add(bundle1); bundles.add(bundle2); PropertyServiceImpl service = new PropertyServiceImpl(new ParenthesesLookUpKeyResolver()); Set<ClearProperty> properties = service.load(bundles); // test with just one lookUp 'lookUp1' List<String> lookUps = new ArrayList<String>(); lookUps.add(expectedLookUp1); lookUps.add(expectedLookUp2); Collection<ClearProperty> filteredProperties = service.filter(properties, lookUps); Assert.assertNotNull(filteredProperties); Assert.assertEquals(filteredProperties.size(), 4); for (ClearProperty filteredProperty : filteredProperties) { String key = filteredProperty.getKey(); String value = filteredProperty.getValue(); String lookUp = filteredProperty.getLookUpKey().getLookUp(); Assert.assertNotNull(filteredProperty.getLookUpKey()); Assert.assertNotNull(filteredProperty.getValue()); Assert.assertNotNull(filteredProperty.getKey()); Assert.assertNotNull(lookUp); if (!(key.equals("foo") || key.equals("stux") || key.equals("flix") || key.equals("baz"))) { Assert.fail("Key must either be foo, stux, flix, or baz"); } if (!(value.equals("bar") || value.equals("flux") || value.equals("glux") || value.equals("waldo"))) { Assert.fail("Key must either be bar, flux, glux, or waldo"); } if (!(lookUp.equals(expectedLookUp1) || lookUp.equals(expectedLookUp2))) { Assert.fail("lookUp either be lookUp1 or lookUp2"); } } }
/** {@inheritDoc} */ @Override protected void update(Object key, Object value) { // If top level active collection, or a derive collection that is being actively // maintained, then apply the update if (!isDerived() || isActive()) { synchronized (_list) { if (key != null) { if (key instanceof Integer) { _list.set((Integer) key, value); if (getItemExpiration() > 0) { _listTimestamps.set((Integer) key, System.currentTimeMillis()); } updated(key, value); } else { LOG.severe( MessageFormat.format( java.util.PropertyResourceBundle.getBundle("active-collection.Messages") .getString("ACTIVE-COLLECTION-8"), key)); } } else { // Can only assume that value maintains its own identity int index = _list.indexOf(value); if (index == -1) { // Can't find updated entry, so log error LOG.severe( MessageFormat.format( java.util.PropertyResourceBundle.getBundle("active-collection.Messages") .getString("ACTIVE-COLLECTION-9"), getName(), value)); } else { _list.set(index, value); if (getItemExpiration() > 0) { _listTimestamps.set(index, System.currentTimeMillis()); } updated(index, value); } } _readCopy = null; } } }
/** Set the parameters object to the settings in the properties object. */ private void loadParams() throws SerialConnectionException { try { PropertyResourceBundle props = (PropertyResourceBundle) PropertyResourceBundle.getBundle(CONFIG_BUNDLE_NAME); System.out.println("BaudRate=" + props.getString("baudRate")); ezlink.info("BaudRate= : " + props.getString("baudRate")); parameters.setBaudRate(props.getString("baudRate")); parameters.setFlowControlIn(props.getString("flowControlIn")); parameters.setFlowControlOut(props.getString("flowControlOut")); parameters.setParity(props.getString("parity")); parameters.setDatabits(props.getString("databits")); parameters.setStopbits(props.getString("stopbits")); parameters.setPIN(props.getString("pin")); parameters.setSMC(props.getString("smc")); parameters.setDriver(props.getString("driver")); parameters.setURL(props.getString("url")); parameters.setUserName(props.getString("username")); parameters.setPassword(props.getString("password")); parameters.setPortName(props.getString("portName")); } catch (Exception exp) { ezlink.info("+++Error While setting parameters : +++"); ezlink.error(new Object(), exp); throw new SerialConnectionException("Error While setting parameters=" + exp.getMessage()); } }
/** * Loads the language for the GUI window. * * @throws IOException It can't be loaded the requested File */ public ResourceBundle loadWindowLanguageStringsResource(String fileName, Locale displayLanguage) throws LanguageExecption { if (localeLang == null) { throw new LanguageExecption("It isn't set a display language (No Locale class is set)."); } try { // Nur laden, wenn von einem anderen Fenster etwas geladen werden soll if (!fileName.equals(guiElement)) { languageResource = PropertyResourceBundle.getBundle(BUNDLE_BASENANE + fileName, displayLanguage); } } catch (MissingResourceException e2) { System.err.println("Cannot load the file with name: " + BUNDLE_BASENANE + fileName); e2.printStackTrace(); throw new LanguageExecption( "(MissingResourceException) Cannot load the file with name: " + BUNDLE_BASENANE + fileName); } catch (NullPointerException e1) { System.err.println("The Inputstream is empty"); e1.printStackTrace(); throw new LanguageExecption("(NullPointerException) The Inputstream is empty"); } return languageResource; }
/** {@inheritDoc} */ @Override protected void insert(Object key, Object value) { // If top level active collection, or a derive collection that is being actively // maintained, then apply the insertion if (!isDerived() || isActive()) { synchronized (_list) { if (key == null) { _list.add(value); if (getItemExpiration() > 0) { _listTimestamps.add(System.currentTimeMillis()); } } else if (key instanceof Integer) { _list.add((Integer) key, value); if (getItemExpiration() > 0) { _listTimestamps.add((Integer) key, System.currentTimeMillis()); } } else { LOG.severe( MessageFormat.format( java.util.PropertyResourceBundle.getBundle("active-collection.Messages") .getString("ACTIVE-COLLECTION-7"), key)); } _readCopy = null; } inserted(key, value); } }
private PropertyResourceBundle getPropertyResourceBundle(String name) { try { return (PropertyResourceBundle) PropertyResourceBundle.getBundle(name, locale); } catch (MissingResourceException e) { return null; } }
/** * This method validates the supplied model object. * * @param obj The model object being validated * @param logger The logger */ public void validate(ModelObject obj, Journal logger) { Recursion elem = (Recursion) obj; ModelObject act = elem.getParent(); if (elem.getLabel() != null) { boolean f_found = false; while (f_found == false && act != null && (act instanceof Protocol) == false) { if (act instanceof RecBlock && ((RecBlock) act).getLabel() != null && ((RecBlock) act).getLabel().equals(elem.getLabel())) { f_found = true; } act = act.getParent(); } if (f_found == false) { logger.error( MessageFormat.format( java.util.PropertyResourceBundle.getBundle("org.scribble.protocol.Messages") .getString("_NO_ENCLOSING_RECUR"), elem.getLabel()), obj.getProperties()); } } }
/** * This method projects a 'global' protocol model to a specified role's 'local' protocol model. * * @param model The 'global' protocol model * @param role The role to project * @param journal Journal for reporting issues * @param context The protocol context * @return The 'local' protocol model */ public ProtocolModel project( ProtocolModel model, Role role, Journal journal, ProtocolContext context) { ProtocolModel ret = null; if (model == null || role == null) { throw new IllegalArgumentException("Model and/or role has not bee specified"); } // Check that the supplied role has been defined within the model // being projected java.util.List<Role> roles = model.getRoles(); int index = roles.indexOf(role); if (index == -1) { throw new IllegalArgumentException( "Role '" + role.getName() + "' is not defined within the protocol model"); } else { // Obtain the role instance actually defined within the model, // as this can be used to locate the appropriate scope to be // projected role = roles.get(index); } // Check that role is defined within a role list, and its parent // link has not inadvertantly been reset if ((role.getParent() instanceof RoleList) == false) { throw new IllegalArgumentException( "Role is not contained within a role list, " + "and is therefore not the declared role"); } DefaultProjectorContext projectorContext = new DefaultProjectorContext(context); ModelObject obj = projectorContext.project(model, role, journal); if (obj != null) { if (obj instanceof ProtocolModel) { ret = (ProtocolModel) obj; } else { String modelName = model.getProtocol().getName(); if (model.getProtocol().getRole() != null) { modelName += "," + model.getProtocol().getRole(); } journal.error( MessageFormat.format( java.util.PropertyResourceBundle.getBundle( "org.scribble.protocol.projection.Messages") .getString("_NOT_PROJECTED_MODEL"), modelName), null); } } return (ret); }
public static synchronized Client getClient() { bundle = PropertyResourceBundle.getBundle("config", Locale.CHINESE); if (client == null) { try { client = new Client(bundle.getString("softwareSerialNo"), bundle.getString("key")); } catch (Exception e) { e.printStackTrace(); } } return client; }
@Test public void testLoadOneFileWithLookUps() { ResourceBundle bundle1 = PropertyResourceBundle.getBundle("propertyServiceImplTest-withLookUps-1"); List<ResourceBundle> bundles = new ArrayList<ResourceBundle>(); bundles.add(bundle1); // using the parentheses resolver for this unit test LookUpKeyResolver resolver = new ParenthesesLookUpKeyResolver(); PropertyServiceImpl service = new PropertyServiceImpl(resolver); Set<ClearProperty> properties = service.load(bundles); Assert.assertNotNull(properties); Assert.assertEquals(properties.size(), 5); for (ClearProperty property : properties) { Assert.assertNotNull(property.getLookUpKey()); String key = property.getKey(); String value = property.getValue(); String lookUp = property.getLookUpKey().getLookUp(); Assert.assertNotNull(key); Assert.assertNotNull(value); // assert keys if (!(key.equals("foo") || key.equals("qix") || key.equals("baz"))) { Assert.fail("invalid key set"); } // assert values if (!(value.equals("boo") || value.equals("bar") || value.equals("waldo") || value.equals("qux") || value.equals("fred"))) { Assert.fail("invalid value set"); } // assert lookUps if (lookUp != null) { if (!(lookUp.equals("lookUp1") || lookUp.equals("lookUp2") || lookUp.equals("lookUp3"))) { Assert.fail("LookUp must either be lookUp1, lookUp2, lookUp3"); } } } }
/** This is the default constructor. */ public RESTServiceDependencyServer() { try { InitialContext ctx = new InitialContext(); _acmManager = (ActiveCollectionManager) ctx.lookup(ACT_COLL_MANAGER); } catch (Exception e) { LOG.log( Level.SEVERE, java.util.PropertyResourceBundle.getBundle("service-dependency-rests.Messages") .getString("SERVICE-DEPENDENCY-RESTS-1"), e); } }
/** * This method loads the rule base associated with the Drools event processor. * * @return The knowledge base */ private KieBase loadRuleBase() { String droolsRuleBase = getRuleName() + ".drl"; try { KieServices ks = KieServices.Factory.get(); KieRepository kr = ks.getRepository(); KieModuleModel kmm = ks.newKieModuleModel(); KieBaseModel kbm = kmm.newKieBaseModel(getRuleName()) .setEqualsBehavior(EqualityBehaviorOption.EQUALITY) .setEventProcessingMode(EventProcessingOption.STREAM); kbm.setDefault(true); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( "src/main/resources/" + kbm.getName() + "/rule1.drl", ks.getResources().newClassPathResource(droolsRuleBase)); kfs.writeKModuleXML(kmm.toXML()); KieBuilder kb = ks.newKieBuilder(kfs); kb.buildAll(); KieContainer container = ks.newKieContainer(kr.getDefaultReleaseId()); KieBase kbase = container.getKieBase(); // TODO: hack it for now, this attribute should be supported in the following drools6 release. System.setProperty("kie.mbean", "enabled"); return kbase; } catch (Throwable e) { LOG.log( Level.SEVERE, MessageFormat.format( java.util.PropertyResourceBundle.getBundle("ep-drools.Messages") .getString("EP-DROOLS-1"), droolsRuleBase, getRuleName()), e); } return (null); }
@Test public void testFilterWithOneFileNoLookUps() { ResourceBundle bundle = PropertyResourceBundle.getBundle("propertyServiceImplTest-noLookUps-1"); Set<ClearProperty> properties = new HashSet<ClearProperty>(); Set<String> keys = bundle.keySet(); for (String key : keys) { String value = bundle.getString(key); LookUpKey lookUpKey = new LookUpKey(null, key, key); ClearProperty clearProperty = new ClearProperty(lookUpKey, value); properties.add(clearProperty); } PropertyServiceImpl service = new PropertyServiceImpl(null); Collection<ClearProperty> filteredProperties = service.filter(properties, new ArrayList<String>()); Assert.assertNotNull(filteredProperties); Assert.assertEquals(properties.size(), 3); for (ClearProperty filteredProperty : filteredProperties) { String key = filteredProperty.getKey(); String value = filteredProperty.getValue(); String lookUp = filteredProperty.getLookUpKey().getLookUp(); Assert.assertNotNull(filteredProperty.getLookUpKey()); Assert.assertNotNull(filteredProperty.getValue()); Assert.assertNotNull(filteredProperty.getKey()); Assert.assertNull(lookUp); if (!(key.equals("foo") || key.equals("baz") || key.equals("qix"))) { Assert.fail("Key must either be foo, baz, or qix"); } if (!(value.equals("bar") || value.equals("waldo") || value.equals("qux"))) { Assert.fail("Key must either be bar, waldo, or qux"); } } }
/** {@inheritDoc} */ @Override protected void remove(Object key, Object value) { // If top level active collection, or a derive collection that is being actively // maintained, then apply the deletion if (!isDerived() || isActive()) { int pos = -1; synchronized (_list) { if (key instanceof Integer) { pos = (Integer) key; } else { pos = _list.indexOf(value); } if (pos != -1) { _list.remove(pos); if (getItemExpiration() > 0) { _listTimestamps.remove(pos); } } else { LOG.severe( MessageFormat.format( java.util.PropertyResourceBundle.getBundle("active-collection.Messages") .getString("ACTIVE-COLLECTION-10"), getName(), value)); } _readCopy = null; } if (pos != -1) { removed(pos, value); } } }
/** * Adds Multi language support using the I18N standard. * * @author Relicum * @version 0.0.1 */ public class I18N { private static final Locale locale = Locale.getDefault(); @NonNls private static final ResourceBundle bundle = PropertyResourceBundle.getBundle("MessagesBundle", locale); // @NonNls // private static final ResourceBundle bundle = ResourceBundle.getBundle(dir + File.separator + // "MessagesBundle", locale); private static final String prefix = bundle.getString("default.prefix"); private static final String infoColor = bundle.getString("default.color.normal"); private static final String altColor = bundle.getString("default.color.alt"); private static final String adminColor = bundle.getString("default.color.admin"); private static final String errorColor = bundle.getString("default.color.error"); private static final String debugPrefix = bundle.getString("default.debug.prefix"); private static final char COLOR_CHAR = '\u00A7'; private static final char SAFE_CHAR = '&'; public static String STRING( @PropertyKey(resourceBundle = "MessagesBundle") final String key, final Object... params) { String value = bundle.getString(key); if (params.length > 0) return MessageFormat.format(value, params); return value; } /** * Send command raw message. * * @param sender the @{@link org.bukkit.command.CommandSender} sender * @param message the {@link java.lang.String} message */ public static void sendRawMessage(CommandSender sender, String message) { sender.sendMessage(message); } public static void sendRawMessage(CommandSender sender, String[] messages) { sender.sendMessage(messages); } public static void sendMessage(CommandSender sender, String[] messages) { for (String s : messages) { sender.sendMessage(format(s)); } } /** * Send command message. * * @param sender the @{@link org.bukkit.command.CommandSender} sender * @param message the {@link java.lang.String} message */ public static void sendMessage(CommandSender sender, String message) { sender.sendMessage(format(message)); } /** * Send command error message. * * @param sender the @{@link org.bukkit.command.CommandSender} sender * @param message the {@link java.lang.String} message */ public static void sendErrorMessage(CommandSender sender, String message) { sender.sendMessage(errorFormat(message)); } /** * Send command admin message. * * @param sender the @{@link org.bukkit.command.CommandSender} sender * @param message the {@link java.lang.String} message */ public static void sendAdminMessage(CommandSender sender, String message) { sender.sendMessage(adminFormat(message)); } /** * Send alternative color command message. * * @param sender the @{@link org.bukkit.command.CommandSender} sender * @param message the {@link java.lang.String} message */ public static void sendAltMessage(CommandSender sender, String message) { sender.sendMessage(altFormat(message)); } /** * Format string. * * @param message the message * @return the string formatted with getPrefix(), message color and converts any other color codes * in message */ public static String format(String message) { return addColor(prefix + infoColor + message); } public static String altFormat(String message) { return addColor(prefix + altColor + message); } /** * Format string. * * @param name the name to use in prefix * @param message the message * @return the string formatted with prefix with custom name, message color and converts any other * color codes in message */ public static String format(String name, String message) { return addColor("&5[&b" + name + "&5] " + message); } /** * Error format. * * @param message the message * @return the string */ public static String errorFormat(String message) { return addColor(prefix + errorColor + message); } /** * Admin format. * * @param message the message * @return the string */ public static String adminFormat(String message) { return addColor(prefix + adminColor + message); } /** * Display a debug message in game. Will only log if debug is set to true in config.yml * * @param sender the sender * @param message the message */ public static void debugGameMessage(CommandSender sender, String message) { sender.sendMessage(addColor(debugPrefix) + addColor(message) + addColor("&r")); } /** * Log to console * * @param message the {@link java.lang.Object} message */ public static void log(Object message) { System.out.println(message); } /** * Convert color. Shade from Bukkit Api * * @param s {@link String} {@link String} the text to convert color chars to correct format * @return the {@link String} line of text which has color formatted */ public static String addColor(String s) { char[] b = s.toCharArray(); for (int i = 0; i < b.length - 1; i++) { if (b[i] == SAFE_CHAR && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { b[i] = COLOR_CHAR; b[i + 1] = Character.toLowerCase(b[i + 1]); } } return new String(b); } /** * Remove color. * * @param message the message * @return the {@link java.lang.String} that has color removed */ public static String removeColor(String message) { return ChatColor.stripColor(message); } /** * Convert color. Shade from Bukkit Api * * @param s {@link String} {@link String} the text to convert color chars to correct format * @return the {@link String} line of text which has color formatted */ public static String addAltColor(String s) { char[] b = s.toCharArray(); for (int i = 0; i < b.length - 1; i++) { if (b[i] == COLOR_CHAR && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { b[i] = SAFE_CHAR; b[i + 1] = Character.toLowerCase(b[i + 1]); } } return new String(b); } public static void clearChat(Player player) { for (int i = 0; i < 100; i++) { player.sendMessage(""); } } public static void clearChat(Player player, int lines) { for (int i = 0; i < lines; i++) { player.sendMessage(""); } } }
/** Epanet exception codes handler. */ public class ENException extends Exception { /** Error text bundle. */ private static final ResourceBundle errorBundle = PropertyResourceBundle.getBundle("Error"); /** Array of arguments to be used in the error string creation. */ private Object[] arguments; /** Epanet error code. */ private int codeID; /** * Get error code. * * @return Code id. */ public int getCodeID() { return codeID; } /** * Contructor from error code id. * * @param id Error code id. */ public ENException(int id) { arguments = null; codeID = id; } /** * Contructor from error code id and multiple arguments. * * @param id Error code id. * @param arg Extra arguments. */ public ENException(int id, Object... arg) { codeID = id; arguments = arg; } /** * Contructor from other exception and multiple arguments. * * @param e * @param arg */ public ENException(ENException e, Object... arg) { arguments = arg; codeID = e.getCodeID(); } /** Get arguments array. */ public Object[] getArguments() { return arguments; } /** * Handles the exception string conversion. * * @return Final error string. */ public String toString() { String str = errorBundle.getString("ERR" + codeID); if (str == null) return String.format("Unknown error message (%d)", codeID); else if (arguments != null) return String.format(str, arguments); return str; } @Override public String getMessage() { return toString(); } }
/** * Adds a resource bundle. This may throw a MissingResourceException that should be handled in the * calling code. * * @param basename The basename of the resource bundle to add. */ public static void add(String basename, Locale locale) { bundles.addFirst(PropertyResourceBundle.getBundle(basename, locale)); }
/** * Returns a Message bundle for a specific locale. * * @return java.util.ResourceBundle * @param inLocale java.util.Locale the desired locale */ public static ResourceBundle getMessageBundle(Locale inLocale) { return PropertyResourceBundle.getBundle(MSG_BUNDLE_BASENAME, inLocale); }
/** @author Chris Bartley ([email protected]) */ public final class RoboticonManagerView implements RoboticonManagerListener { private static final Logger LOG = Logger.getLogger(RoboticonManagerView.class); // @jve:decl-index=0: private static final PropertyResourceBundle RESOURCES = (PropertyResourceBundle) PropertyResourceBundle.getBundle( RoboticonManagerView.class.getName()); // @jve:decl-index=0: private static final Font FONT = GUIConstants.FONT_SMALL; private static final Font BOLD_FONT = FONT.deriveFont(Font.BOLD); private final SortedRoboticonManagerModel privateSortedRoboticonModel; private final SortedRoboticonManagerModel publicSortedRoboticonModel; private final DragAndDropJList privateList; private final DragAndDropJList publicList; private RoboticonListPanel privateListPanel = null; private RoboticonListPanel publicListPanel = null; private JPanel listPanel = null; // @jve:decl-index=0:visual-constraint="179,19" public RoboticonManagerView( final RoboticonManagerModel roboticonManagerModel, final RoboticonManagerModel publicRoboticonManagerModel) { privateSortedRoboticonModel = new SortedRoboticonManagerModel(roboticonManagerModel, SortOrder.TYPE); privateList = new DragAndDropJList(privateSortedRoboticonModel); privateList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); privateList.setLayoutOrientation(DragAndDropJList.VERTICAL); privateList.setCellRenderer(new MyListCellRenderer()); privateList.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); privateList.setDragEnabled(true); privateList.setSelectionBackground(Color.orange); privateList.setSelectionForeground(Color.white); publicSortedRoboticonModel = new SortedRoboticonManagerModel(publicRoboticonManagerModel, SortOrder.NAME); publicList = new DragAndDropJList(publicSortedRoboticonModel); publicList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); publicList.setLayoutOrientation(DragAndDropJList.VERTICAL); publicList.setCellRenderer(new MyListCellRenderer()); publicList.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); publicList.setDragEnabled(true); publicList.setSelectionBackground(Color.orange); publicList.setSelectionForeground(Color.white); getListPanel(); } public Component getRoboticonListComponent() { return listPanel; } public void contentsChanged() { LOG.trace("RoboticonManagerView.contentsChanged()"); } public void setEnabled(final boolean isEnabled) { privateList.setEnabled(isEnabled); // privateListPanel.setIsSupported(isEnabled); //not actually doing anything? // publicListPanel.setIsSupported(isEnabled); //not actually doing anything? // listPanel.setIsSupported(isEnabled); //not actually doing anything? publicList.setEnabled(isEnabled); } private final class MyListCellRenderer extends JLabel implements ListCellRenderer { private static final long serialVersionUID = 1769903297941249743L; private MyListCellRenderer() { setOpaque(true); setBorder(BorderFactory.createEmptyBorder()); setHorizontalAlignment(JLabel.LEFT); setVerticalTextPosition(JLabel.CENTER); setFont(FONT); } public Component getListCellRendererComponent( final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { final RoboticonFile roboticonFile = (RoboticonFile) value; JLabel label = new JLabel(); label.setOpaque(true); label.setBorder(BorderFactory.createEmptyBorder()); label.setHorizontalAlignment(JLabel.LEFT); label.setVerticalTextPosition(JLabel.CENTER); label.setFont(FONT); label.setEnabled(list.isEnabled()); label.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground()); label.setBackground(isSelected ? list.getSelectionBackground() : list.getBackground()); // BOLD text if sequence if (roboticonFile.roboticonType.equals(RoboticonType.SEQUENCE)) { label.setFont(BOLD_FONT); } String fileName = roboticonFile == null ? "unknown" : roboticonFile.getName(); if (fileName.lastIndexOf('.') != -1) { fileName = fileName.substring(0, fileName.lastIndexOf('.')); } label.setText(fileName); String toolTip = null; if (roboticonFile != null) { toolTip = roboticonFile.senderId; if (toolTip.length() == 0) { toolTip = roboticonFile.getAbsolutePath(); } } label.setToolTipText(toolTip); return label; } } /** * This method initializes privateListPanel * * @return javax.swing.JPanel */ private RoboticonListPanel getPrivateListPanel() { if (privateListPanel == null) { privateListPanel = new RoboticonListPanel( RESOURCES.getString("label.roboticons"), privateList, new String[] { SortOrder.NAME.toString(), SortOrder.TYPE.toString(), SortOrder.DATE.toString() }, 1, new Dimension(200, 250)); privateListPanel.addSortOrderListener( new SortOrderListenerIf() { public void sortOrderChanged(SortOrder newOrder) { privateSortedRoboticonModel.setSortOrder(newOrder); } }); } return privateListPanel; } /** * This method initializes publicListPanel * * @return javax.swing.JPanel */ private RoboticonListPanel getPublicListPanel() { if (publicListPanel == null) { publicListPanel = new RoboticonListPanel( RESOURCES.getString("label.shared-roboticons"), publicList, new String[] { SortOrder.NAME.toString(), SortOrder.TYPE.toString(), SortOrder.DATE.toString(), SortOrder.OWNER.toString() }, 0, new Dimension(200, 250)); publicListPanel.addSortOrderListener( new SortOrderListenerIf() { public void sortOrderChanged(SortOrder newOrder) { publicSortedRoboticonModel.setSortOrder(newOrder); } }); } return publicListPanel; } /** * This method initializes listPanel * * @return javax.swing.JPanel */ private JPanel getListPanel() { if (listPanel == null) { listPanel = new JPanel(); listPanel.setLayout(new BorderLayout()); listPanel.setPreferredSize(new Dimension(225, 400)); listPanel.add(getPublicListPanel().getPanel(), BorderLayout.SOUTH); listPanel.add(Box.createRigidArea(new Dimension(5, 5))); listPanel.add(getPrivateListPanel().getPanel(), BorderLayout.NORTH); listPanel.add(Box.createRigidArea(new Dimension(5, 5))); listPanel.setBackground(Color.orange); } return listPanel; } public SortedRoboticonManagerModel getPublicSortedRoboticonModel() { return publicSortedRoboticonModel; } public JList getPrivateListComponent() { return privateList; } public JList getPublicListComponent() { return publicList; } }
public static synchronized String getKey(String key) { bundle = PropertyResourceBundle.getBundle("config"); return bundle.getString(key); }
/** * This method handles queries. * * @param width The optional width * @return The list of objects * @throws Exception Failed to query */ @GET @Path("/overview") @Produces("image/svg+xml") public String overview(@DefaultValue("0") @QueryParam("width") int width) throws Exception { String ret = ""; // Obtain service definition collection if (_acmManager != null && _servDefns == null) { _servDefns = _acmManager.getActiveCollection("ServiceDefinitions"); } if (_acmManager != null && _situations == null) { _situations = _acmManager.getActiveCollection("Situations"); } if (_servDefns == null) { throw new Exception("Service definitions are not available"); } if (_situations == null) { throw new Exception("Situations are not available"); } java.util.Set<ServiceDefinition> sds = new java.util.HashSet<ServiceDefinition>(); for (Object entry : _servDefns) { if (entry instanceof ActiveMap.Entry && ((ActiveMap.Entry) entry).getValue() instanceof ServiceDefinition) { sds.add((ServiceDefinition) ((ActiveMap.Entry) entry).getValue()); } } java.util.List<Situation> situations = new java.util.ArrayList<Situation>(); for (Object obj : _situations) { if (obj instanceof Situation) { situations.add((Situation) obj); } } ServiceGraph graph = ServiceDependencyBuilder.buildGraph(sds, situations); if (graph == null) { throw new Exception("Failed to generate service dependency overview"); } graph.setDescription("Generated: " + new java.util.Date()); ServiceGraphLayoutImpl layout = new ServiceGraphLayoutImpl(); layout.layout(graph); // Check some of the dimensions SVGServiceGraphGenerator generator = new SVGServiceGraphGenerator(); MVELColorSelector selector = new MVELColorSelector(); selector.setScriptLocation("ColorSelector.mvel"); try { selector.init(); generator.setColorSelector(selector); } catch (Exception e) { LOG.log( Level.SEVERE, java.util.PropertyResourceBundle.getBundle("service-dependency-rests.Messages") .getString("SERVICE-DEPENDENCY-RESTS-2"), e); } java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream(); generator.generate(graph, width, os); os.close(); ret = new String(os.toByteArray()); if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Overview=" + ret); } return (ret); }
/** @author Chris Bartley ([email protected]) */ public final class PropertyInspector extends BaseGUIClient { private static final Logger LOG = Logger.getLogger(PropertyInspector.class); private static final PropertyResourceBundle RESOURCES = (PropertyResourceBundle) PropertyResourceBundle.getBundle(PropertyInspector.class.getName()); /** The application name (appears in the title bar) */ private static final String APPLICATION_NAME = RESOURCES.getString("application.name"); /** Properties file used to setup Ice for this application */ private static final String ICE_DIRECT_CONNECT_PROPERTIES_FILE = "/edu/cmu/ri/mrpl/TeRK/client/propertyinspector/PropertyInspector.direct-connect.ice.properties"; private static final String ICE_RELAY_PROPERTIES_FILE = "/edu/cmu/ri/mrpl/TeRK/client/propertyinspector/PropertyInspector.relay.ice.properties"; private static final Dimension TABLE_DIMENSIONS = new Dimension(300, 300); private static final String COLUMN_NAME_KEY = RESOURCES.getString("table.column.name.keys"); private static final String COLUMN_NAME_VALUE = RESOURCES.getString("table.column.name.values"); private static final String SERVICE_NAME_QWERK = RESOURCES.getString("service.name.qwerk"); private static final String SERVICE_NAME_ANALOG = RESOURCES.getString("service.name.analog"); private static final String SERVICE_NAME_AUDIO = RESOURCES.getString("service.name.audio"); private static final String SERVICE_NAME_DIGITAL_IN = RESOURCES.getString("service.name.digital-in"); private static final String SERVICE_NAME_DIGITAL_OUT = RESOURCES.getString("service.name.digital-out"); private static final String SERVICE_NAME_LED = RESOURCES.getString("service.name.led"); private static final String SERVICE_NAME_MOTOR = RESOURCES.getString("service.name.motor"); private static final String SERVICE_NAME_SERIAL = RESOURCES.getString("service.name.serial"); private static final String SERVICE_NAME_SERVO = RESOURCES.getString("service.name.servo"); private static final String SERVICE_NAME_VIDEO = RESOURCES.getString("service.name.video"); private static final String[] SERVICE_NAMES = new String[] { SERVICE_NAME_QWERK, SERVICE_NAME_ANALOG, SERVICE_NAME_AUDIO, SERVICE_NAME_DIGITAL_IN, SERVICE_NAME_DIGITAL_OUT, SERVICE_NAME_LED, SERVICE_NAME_MOTOR, SERVICE_NAME_SERIAL, SERVICE_NAME_SERVO, SERVICE_NAME_VIDEO }; private final JButton connectOrDisconnectButton = getConnectDisconnectButton(); private final JTextField propertyKeyTextField = new JTextField(25); private final JTextField propertyValueTextField = new JTextField(25); private final JComboBox createPropertyServiceComboBox = new JComboBox(SERVICE_NAMES); private final JButton createPropertyButton = GUIConstants.createButton(RESOURCES.getString("button.label.create")); private final JComboBox viewPropertiesServiceComboBox = new JComboBox(SERVICE_NAMES); private final JButton reloadPropertiesButton = GUIConstants.createButton(RESOURCES.getString("button.label.reload")); private PropertiesTableModel propertiesTableModel = new PropertiesTableModel(); private final JTable propertiesTable = new JTable(propertiesTableModel); private final Map<String, String> serviceNameToTypeIdMap; private final TextComponentValidator isNonEmptyValidator = new TextComponentValidator() { public boolean isValid(final JTextComponent textComponent) { return textComponent != null && isTextComponentNonEmpty(textComponent); } }; private final KeyListener propertyKeyKeyListener = new EnableButtonIfTextFieldIsValidKeyAdapter( createPropertyButton, propertyKeyTextField, isNonEmptyValidator); private final ActionListener viewPropertiesAction = new ViewPropertiesAction(); private final Runnable readonlyPropertyError = new ErrorMessageDialogRunnable( RESOURCES.getString("dialog.message.cannot-overwrite-read-only-property"), RESOURCES.getString("dialog.title.cannot-overwrite-read-only-property")); public static void main(final String[] args) { // Schedule a job for the event-dispatching thread: creating and showing this application's GUI. SwingUtilities.invokeLater( new Runnable() { public void run() { new PropertyInspector(); } }); } private PropertyInspector() { super(APPLICATION_NAME, ICE_RELAY_PROPERTIES_FILE, ICE_DIRECT_CONNECT_PROPERTIES_FILE); setGUIClientHelperEventHandler( new GUIClientHelperEventHandlerAdapter() { public void executeAfterEstablishingConnectionToQwerk(final String qwerkUserId) { updateViewPropertiesTable(); } public void toggleGUIElementState(final boolean isEnabled) { toggleGUIElements(isEnabled); } }); // CONFIGURE GUI ELEMENTS // ======================================================================================== this.setFocusTraversalPolicy(new MyFocusTraversalPolicy()); createPropertyButton.addActionListener(new CreatePropertyAction()); final Map<String, String> tempServiceNameToTypeIdMap = new HashMap<String, String>(); tempServiceNameToTypeIdMap.put(SERVICE_NAME_ANALOG, AnalogInputsService.TYPE_ID); tempServiceNameToTypeIdMap.put(SERVICE_NAME_AUDIO, AudioService.TYPE_ID); tempServiceNameToTypeIdMap.put(SERVICE_NAME_DIGITAL_IN, DigitalInService.TYPE_ID); tempServiceNameToTypeIdMap.put(SERVICE_NAME_DIGITAL_OUT, DigitalOutService.TYPE_ID); tempServiceNameToTypeIdMap.put(SERVICE_NAME_LED, LEDService.TYPE_ID); tempServiceNameToTypeIdMap.put(SERVICE_NAME_MOTOR, BackEMFMotorService.TYPE_ID); tempServiceNameToTypeIdMap.put(SERVICE_NAME_SERIAL, SerialIOService.TYPE_ID); tempServiceNameToTypeIdMap.put(SERVICE_NAME_SERVO, ServoService.TYPE_ID); tempServiceNameToTypeIdMap.put(SERVICE_NAME_VIDEO, VideoStreamService.TYPE_ID); serviceNameToTypeIdMap = Collections.unmodifiableMap(tempServiceNameToTypeIdMap); viewPropertiesServiceComboBox.addItemListener( new ItemListener() { public void itemStateChanged(final ItemEvent itemEvent) { updateViewPropertiesTable(); } }); reloadPropertiesButton.addActionListener( new ActionListener() { public void actionPerformed(final ActionEvent actionEvent) { updateViewPropertiesTable(); } }); final JScrollPane propertiesTableScrollPane = new JScrollPane(propertiesTable); propertiesTableScrollPane.setMinimumSize(TABLE_DIMENSIONS); propertiesTableScrollPane.setMaximumSize(TABLE_DIMENSIONS); propertiesTableScrollPane.setPreferredSize(TABLE_DIMENSIONS); toggleGUIElements(false); propertyKeyTextField.addKeyListener(propertyKeyKeyListener); // LAYOUT GUI ELEMENTS // =========================================================================================== // create a panel to hold the connect/disconnect button and the connection state labels final JPanel connectionPanel = new JPanel(new SpringLayout()); connectionPanel.add(connectOrDisconnectButton); connectionPanel.add(getConnectionStatePanel()); SpringLayoutUtilities.makeCompactGrid( connectionPanel, 1, 2, // rows, cols 0, 0, // initX, initY 10, 10); // xPad, yPad final JPanel createPropertyPanel = new JPanel(new SpringLayout()); createPropertyPanel.setBorder( BorderFactory.createTitledBorder(RESOURCES.getString("border.title.create-property"))); createPropertyPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.service"))); createPropertyPanel.add(createPropertyServiceComboBox); createPropertyPanel.add(createPropertyButton); createPropertyPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.key"))); createPropertyPanel.add(propertyKeyTextField); createPropertyPanel.add(Box.createGlue()); createPropertyPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.value"))); createPropertyPanel.add(propertyValueTextField); createPropertyPanel.add(Box.createGlue()); SpringLayoutUtilities.makeCompactGrid( createPropertyPanel, 3, 3, // rows, cols 5, 5, // initX, initY 5, 5); // xPad, yPad final JPanel serviceChooserPanel = new JPanel(new SpringLayout()); serviceChooserPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.service"))); serviceChooserPanel.add(viewPropertiesServiceComboBox); serviceChooserPanel.add(reloadPropertiesButton); SpringLayoutUtilities.makeCompactGrid( serviceChooserPanel, 1, 3, // rows, cols 5, 5, // initX, initY 5, 5); // xPad, yPad final JPanel viewPropertiesPanel = new JPanel(new SpringLayout()); viewPropertiesPanel.setBorder( BorderFactory.createTitledBorder(RESOURCES.getString("border.title.view-propertes"))); viewPropertiesPanel.add(serviceChooserPanel); viewPropertiesPanel.add(propertiesTableScrollPane); SpringLayoutUtilities.makeCompactGrid( viewPropertiesPanel, 2, 1, // rows, cols 5, 5, // initX, initY 5, 5); // xPad, yPad // Layout the main content pane using SpringLayout getMainContentPane().setLayout(new SpringLayout()); getMainContentPane().add(connectionPanel); getMainContentPane().add(createPropertyPanel); getMainContentPane().add(viewPropertiesPanel); SpringLayoutUtilities.makeCompactGrid( getMainContentPane(), 3, 1, // rows, cols 10, 10, // initX, initY 10, 10); // xPad, yPad pack(); setLocationRelativeTo(null); // center the window on the screen setVisible(true); } private void toggleGUIElements(final boolean isEnabled) { propertyKeyTextField.setEnabled(isEnabled); propertyValueTextField.setEnabled(isEnabled); createPropertyServiceComboBox.setEnabled(isEnabled); createPropertyButton.setEnabled(isEnabled && isNonEmptyValidator.isValid(propertyKeyTextField)); viewPropertiesServiceComboBox.setEnabled(isEnabled); reloadPropertiesButton.setEnabled(isEnabled); propertiesTable.setEnabled(isEnabled); } private PropertyManager getPropertyManagerByServiceName(final String serviceName) { if (SERVICE_NAME_QWERK.equals(serviceName)) { return getQwerkController(); } else { final String serviceTypeId = serviceNameToTypeIdMap.get(serviceName); return getQwerkController().getServiceByTypeId(serviceTypeId); } } private void updateViewPropertiesTable() { viewPropertiesAction.actionPerformed(null); } private static boolean isTextComponentNonEmpty(final JTextComponent textField) { final String text1 = textField.getText(); final String trimmedText1 = (text1 != null) ? text1.trim() : null; return (trimmedText1 != null) && (trimmedText1.length() > 0); } /** Retrieves the value from the specified text field as a {@link String}. */ @SuppressWarnings({"UnusedCatchParameter"}) private String getTextComponentValueAsString(final JTextComponent textComponent) { if (SwingUtilities.isEventDispatchThread()) { final String textFieldValue; try { final String text1 = textComponent.getText(); textFieldValue = (text1 != null) ? text1.trim() : null; } catch (Exception e) { LOG.error("Exception while getting the value from text field. Returning null instead.", e); return null; } return textFieldValue; } else { final String[] textFieldValue = new String[1]; try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { textFieldValue[0] = textComponent.getText(); } }); } catch (Exception e) { LOG.error("Exception while getting the value from text field. Returning null instead.", e); return null; } return textFieldValue[0]; } } private static interface TextComponentValidator { boolean isValid(final JTextComponent textComponent); } private static final class EnableButtonIfTextFieldIsValidKeyAdapter extends KeyAdapter { private final JButton button; private final JTextComponent textComponent; private final TextComponentValidator validator; private EnableButtonIfTextFieldIsValidKeyAdapter( final JButton button, final JTextComponent textComponent, final TextComponentValidator validator) { this.button = button; this.textComponent = textComponent; this.validator = validator; } public void keyReleased(final KeyEvent keyEvent) { button.setEnabled(validator.isValid(textComponent)); } } private final class PropertiesTableModel extends AbstractTableModel { private final List<String> keys = new ArrayList<String>(); private final List<String> values = new ArrayList<String>(); private void update(final Map<String, String> properties) { keys.clear(); values.clear(); if (properties != null) { final SortedMap<String, String> sortedProperties = new TreeMap<String, String>(properties); keys.addAll(sortedProperties.keySet()); values.addAll(sortedProperties.values()); } fireTableDataChanged(); } public int getRowCount() { return keys.size(); } public String getColumnName(final int i) { return (i == 0) ? COLUMN_NAME_KEY : COLUMN_NAME_VALUE; } public int getColumnCount() { return 2; } public Object getValueAt(final int row, final int col) { if (col == 0) { return keys.get(row); } else if (col == 1) { return values.get(row); } return null; } } private final class CreatePropertyAction extends AbstractTimeConsumingAction { private String key; private String value; private String serviceName; private PropertyManager propertyManager; private CreatePropertyAction() { super(PropertyInspector.this); } protected void executeGUIActionBefore() { propertyKeyTextField.setEnabled(false); propertyValueTextField.setEnabled(false); createPropertyServiceComboBox.setEnabled(false); key = getTextComponentValueAsString(propertyKeyTextField); value = getTextComponentValueAsString(propertyValueTextField); serviceName = createPropertyServiceComboBox.getSelectedItem().toString(); propertyManager = getPropertyManagerByServiceName(serviceName); } @SuppressWarnings({"UnusedCatchParameter"}) protected Object executeTimeConsumingAction() { if (propertyManager != null) { try { propertyManager.setProperty(key, value); } catch (ReadOnlyPropertyException e) { LOG.info("Cannot overwrite read-only property [" + key + "]"); return false; } } return true; } protected void executeGUIActionAfter(final Object resultOfTimeConsumingAction) { if (!(Boolean) resultOfTimeConsumingAction) { SwingUtilities.invokeLater(readonlyPropertyError); } final String currentlyDisplayedService = viewPropertiesServiceComboBox.getSelectedItem().toString(); viewPropertiesServiceComboBox.setSelectedItem(serviceName); // force a reload if the service name isn't different if (currentlyDisplayedService.equals(serviceName)) { updateViewPropertiesTable(); } propertyKeyTextField.setEnabled(true); propertyValueTextField.setEnabled(true); createPropertyServiceComboBox.setEnabled(true); } } private final class ViewPropertiesAction extends AbstractTimeConsumingAction { private PropertyManager propertyManager; private ViewPropertiesAction() { super(PropertyInspector.this); } protected void executeGUIActionBefore() { viewPropertiesServiceComboBox.setEnabled(false); final String serviceName = viewPropertiesServiceComboBox.getSelectedItem().toString(); propertyManager = getPropertyManagerByServiceName(serviceName); } protected Object executeTimeConsumingAction() { if (propertyManager != null) { return propertyManager.getProperties(); } return null; } @SuppressWarnings({"unchecked"}) protected void executeGUIActionAfter(final Object resultOfTimeConsumingAction) { propertiesTableModel.update((Map<String, String>) resultOfTimeConsumingAction); viewPropertiesServiceComboBox.setEnabled(true); } } private class ErrorMessageDialogRunnable implements Runnable { private final String message; private final String title; private ErrorMessageDialogRunnable(final String message, final String title) { this.message = message; this.title = title; } public void run() { JOptionPane.showMessageDialog( PropertyInspector.this, message, title, JOptionPane.ERROR_MESSAGE); } } private class MyFocusTraversalPolicy extends FocusTraversalPolicy { public Component getComponentAfter(final Container container, final Component component) { if (component.equals(connectOrDisconnectButton)) { return getEnabledComponentAfter(container, createPropertyServiceComboBox); } else if (component.equals(createPropertyServiceComboBox)) { return getEnabledComponentAfter(container, propertyKeyTextField); } else if (component.equals(propertyKeyTextField)) { return getEnabledComponentAfter(container, propertyValueTextField); } else if (component.equals(propertyValueTextField)) { return getEnabledComponentAfter(container, createPropertyButton); } else if (component.equals(createPropertyButton)) { return getEnabledComponentAfter(container, viewPropertiesServiceComboBox); } else if (component.equals(viewPropertiesServiceComboBox)) { return getEnabledComponentAfter(container, reloadPropertiesButton); } else if (component.equals(reloadPropertiesButton)) { return getEnabledComponentAfter(container, connectOrDisconnectButton); } return null; } public Component getComponentBefore(final Container container, final Component component) { if (component.equals(connectOrDisconnectButton)) { return getEnabledComponentBefore(container, reloadPropertiesButton); } else if (component.equals(createPropertyServiceComboBox)) { return getEnabledComponentBefore(container, connectOrDisconnectButton); } else if (component.equals(propertyKeyTextField)) { return getEnabledComponentBefore(container, createPropertyServiceComboBox); } else if (component.equals(propertyValueTextField)) { return getEnabledComponentBefore(container, propertyKeyTextField); } else if (component.equals(createPropertyButton)) { return getEnabledComponentBefore(container, propertyValueTextField); } else if (component.equals(viewPropertiesServiceComboBox)) { return getEnabledComponentBefore(container, createPropertyButton); } else if (component.equals(reloadPropertiesButton)) { return getEnabledComponentBefore(container, viewPropertiesServiceComboBox); } return null; } private Component getEnabledComponentAfter( final Container container, final Component component) { return (component.isEnabled() ? component : getComponentAfter(container, component)); } private Component getEnabledComponentBefore( final Container container, final Component component) { return (component.isEnabled() ? component : getComponentBefore(container, component)); } public Component getFirstComponent(final Container container) { return connectOrDisconnectButton; } public Component getLastComponent(final Container container) { return createPropertyButton; } public Component getDefaultComponent(final Container container) { return connectOrDisconnectButton; } } }