List of usage examples for org.apache.commons.configuration CompositeConfiguration getString
public String getString(String key)
From source file:org.ejbca.ui.cli.config.cmp.UploadFileCommand.java
private void readConfigurations(CompositeConfiguration config, String alias) { // if the alias does not already exist, create it. getCmpConfiguration().addAlias(alias); // Reading all relevant configurations from file. boolean populated = false; Set<String> keys = CmpConfiguration.getAllAliasKeys(alias); Iterator<String> itr = keys.iterator(); while (itr.hasNext()) { String key = itr.next();/* ww w. j a v a2s. c o m*/ if (config.containsKey(key)) { populated = true; String value = config.getString(key); getCmpConfiguration().setValue(key, value, alias); log.info("Setting value: " + key + "=" + value); } } // Save the new configurations. if (populated) { try { getGlobalConfigurationSession().saveConfiguration(getAuthenticationToken(), getCmpConfiguration()); log.info("\nNew configurations saved successfully."); log.info( "If there are any issues with the configurations, check them in the AdminGUI and click 'Save'"); getGlobalConfigurationSession().flushConfigurationCache(CmpConfiguration.CMP_CONFIGURATION_ID); } catch (AuthorizationDeniedException e) { log.error("Failed to save configuration from file: " + e.getLocalizedMessage()); } } else { getCmpConfiguration().removeAlias(alias); log.info("No relevent CMP configurations found with alias '" + alias + "' in the file."); } }
From source file:org.ejbca.ui.cli.config.scep.UploadFileCommand.java
private void readConfigurations(CompositeConfiguration config, String alias) { ScepConfiguration scepConfig = getScepConfiguration(); // if the alias does not already exist, create it. scepConfig.addAlias(alias);/* ww w. j a v a 2s.co m*/ // Reading all relevant configurations from file. boolean populated = false; Set<String> keys = ScepConfiguration.getAllAliasKeys(alias); @SuppressWarnings("unchecked") Iterator<String> itr = config.getKeys(); while (itr.hasNext()) { String key = itr.next(); String value = config.getString(key); if (StringUtils.contains(key, ScepConfiguration.SCEP_RAMODE_OLD)) { value = StringUtils.equalsIgnoreCase(config.getString(key), "true") ? "ra" : "ca"; key = alias + "." + ScepConfiguration.SCEP_OPERATIONMODE; } if (keys.contains(key)) { populated = true; scepConfig.setValue(key, value, alias); log.info("Setting value: " + key + "=" + value); } } // Save the new configurations. if (populated) { try { getGlobalConfigurationSession().saveConfiguration(getAuthenticationToken(), scepConfig); log.info("\nNew configurations saved successfully."); log.info( "If there are any issues with the configurations, check them in the AdminGUI and click 'Save'"); getGlobalConfigurationSession().flushConfigurationCache(ScepConfiguration.SCEP_CONFIGURATION_ID); } catch (AuthorizationDeniedException e) { log.error("Failed to save configuration from file: " + e.getLocalizedMessage()); } } else { scepConfig.removeAlias(alias); log.info("No relevent CMP configurations found with alias '" + alias + "' in the file."); } }
From source file:org.mozilla.testopia.transport.TestopiaXmlRpcClient.java
/** * Creates XML-RPC client configuration. * @param configuration/*from w w w . j a v a 2 s . c om*/ * @return XmlRpcClientConfig */ private XmlRpcClientConfig createXmlRpcClientConfiguration(CompositeConfiguration configuration) { final XmlRpcClientConfigImpl xmlRpcClientConfig = new XmlRpcClientConfigImpl(); // basic settings xmlRpcClientConfig.setEnabledForExtensions(true); // xmlrpc basic encoding xmlRpcClientConfig.setBasicEncoding(configuration.getString(XMLRPC_BASIC_ENCODING)); xmlRpcClientConfig.setBasicPassword(configuration.getString(XMLRPC_BASIC_PASSWORD)); xmlRpcClientConfig.setBasicUserName(configuration.getString(XMLRPC_BASIC_USERNAME)); // connectino timeout try { xmlRpcClientConfig.setConnectionTimeout(configuration.getInt(XMLRPC_CONNECTION_TIMEOUT)); } catch (ConversionException ce) { this.debug(ce); } catch (NoSuchElementException nsee) { this.debug(nsee); } // content length optional try { xmlRpcClientConfig.setContentLengthOptional(configuration.getBoolean(XMLRPC_CONTENT_LENGTH_OPTIONAL)); } catch (ConversionException ce) { this.debug(ce); } catch (NoSuchElementException nsee) { this.debug(nsee); } // xmlrpc enabled for exceptions try { xmlRpcClientConfig.setEnabledForExceptions(configuration.getBoolean(XMLRPC_ENABLED_FOR_EXCEPTIONS)); } catch (ConversionException ce) { this.debug(ce); } catch (NoSuchElementException nsee) { this.debug(nsee); } // xmlrpc encoding xmlRpcClientConfig.setEncoding(configuration.getString(XMLRPC_ENCODING)); // gzip compression try { xmlRpcClientConfig.setGzipCompressing(configuration.getBoolean(XMLRPC_GZIP_COMPRESSION)); } catch (ConversionException ce) { this.debug(ce); } catch (NoSuchElementException nsee) { this.debug(nsee); } // gzip request try { xmlRpcClientConfig.setGzipRequesting(configuration.getBoolean(XMLRPC_GZIP_REQUESTING)); } catch (ConversionException ce) { this.debug(ce); } catch (NoSuchElementException nsee) { this.debug(nsee); } // timeout try { xmlRpcClientConfig.setReplyTimeout(configuration.getInt(XMLRPC_REPLY_TIMEOUT)); } catch (ConversionException ce) { this.debug(ce); } catch (NoSuchElementException nsee) { this.debug(nsee); } // user agent xmlRpcClientConfig.setUserAgent(configuration.getString(XMLRPC_USER_AGENT)); return xmlRpcClientConfig; }
From source file:org.overlord.sramp.ui.server.listeners.Initializer.java
/** * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) *//* w w w . j a v a 2 s . c o m*/ @Override public void contextInitialized(ServletContextEvent event) { try { CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); config.addConfiguration(new JNDIConfiguration("java:comp/env/overlord/s-ramp-ui")); config.addConfiguration(new PropertiesConfiguration( Initializer.class.getResource("/META-INF/config/org.overlord.sramp.ui.server.api.properties"))); System.out.println("S-RAMP user interface configuration loaded. S-RAMP Atom API endpoint: " + config.getString("s-ramp.atom-api.endpoint")); // Now initialize the S-RAMP Atom API Client singleton SrampAtomApiClient.init(config); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.rdswicthboard.utils.rdf.oai.App.java
public static void main(String[] args) { // create the command line parser CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file"); options.addOption("o", PROPERTY_OUTPUT_FILE, true, "output OAI-PMH XML file (default is " + DEFAULT_OUTPUT_FILE + ")"); options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (" + PROPERTIES_FILE + ")"); options.addOption("s", PROPERTY_SET_SPEC, true, "set spec value (default is " + DEFAULT_SET_SPEC + ")"); options.addOption("I", PROPERTY_INPUT_ENCODING, true, "input file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("O", PROPERTY_OUTPUT_ENCODING, true, "output file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding"); options.addOption("h", PROPERTY_HELP, false, "print this message"); try {/*from w w w . j a v a 2s.com*/ // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption(PROPERTY_HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar rdf2oai-[verion].jar [PARAMETERS] [INPUT FILE] [OUTPUT FILE]", options); System.exit(0); } // variables to store program properties CompositeConfiguration config = new CompositeConfiguration(); config.setProperty(PROPERTY_OUTPUT_FILE, DEFAULT_OUTPUT_FILE); config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_SET_SPEC, DEFAULT_SET_SPEC); config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT); // check if arguments has input file properties if (line.hasOption(PROPERTY_CONFIG_FILE)) { // if it does, load the specified configuration file Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE)); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } else throw new Exception("Invalid configuration file: " + defaultConfig.toString()); } else { // if it not, try to load default configurationfile Path defaultConfig = Paths.get(PROPERTIES_FILE); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } } // check if arguments has input file if (line.hasOption(PROPERTY_INPUT_FILE)) config.setProperty(PROPERTY_INPUT_FILE, line.getOptionValue(PROPERTY_INPUT_FILE)); // check if arguments has output file if (line.hasOption(PROPERTY_OUTPUT_FILE)) config.setProperty(PROPERTY_OUTPUT_FILE, line.getOptionValue(PROPERTY_OUTPUT_FILE)); // check if arguments has set spec name if (line.hasOption(PROPERTY_SET_SPEC)) config.setProperty(PROPERTY_SET_SPEC, line.getOptionValue(PROPERTY_SET_SPEC)); // check if arguments has input encoding if (line.hasOption(PROPERTY_INPUT_ENCODING)) config.setProperty(PROPERTY_INPUT_ENCODING, line.getOptionValue(PROPERTY_INPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_OUTPUT_ENCODING)) config.setProperty(PROPERTY_OUTPUT_ENCODING, line.getOptionValue(PROPERTY_OUTPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_FORMAT_OUTPUT)) config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes"); // check if arguments has input file without a key if (line.getArgs().length > 0) { config.setProperty(PROPERTY_INPUT_FILE, line.getArgs()[0]); // check if arguments has output file without a key if (line.getArgs().length > 1) { config.setProperty(PROPERTY_OUTPUT_FILE, line.getArgs()[1]); // check if there is too many arguments if (line.getArgs().length > 2) throw new Exception("Too many arguments"); } } // The program has default output file, but input file must be presented if (!config.containsKey(PROPERTY_INPUT_FILE)) throw new Exception("Please specify input file"); // extract input file String inputFile = config.getString(PROPERTY_INPUT_FILE); // extract output file String outputFile = config.getString(PROPERTY_OUTPUT_FILE); // extract set spec String setSpecName = config.getString(PROPERTY_SET_SPEC); // extract encoding String inputEncoding = config.getString(PROPERTY_INPUT_ENCODING); String outputEncoding = config.getString(PROPERTY_OUTPUT_ENCODING); boolean formatOutput = config.getBoolean(PROPERTY_FORMAT_OUTPUT); // test if source is an regular file and it is readable Path source = Paths.get(inputFile); if (!Files.isRegularFile(source)) throw new Exception("The input file: " + source.toString() + " is not an regular file"); if (!Files.isReadable(source)) throw new Exception("The input file: " + source.toString() + " is not readable"); Path target = Paths.get(outputFile); if (Files.exists(target)) { if (!Files.isRegularFile(target)) throw new Exception("The output file: " + target.toString() + " is not an regular file"); if (!Files.isWritable(target)) throw new Exception("The output file: " + target.toString() + " is not writable"); } // create and setup document builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // create new document builder DocumentBuilder builder = factory.newDocumentBuilder(); // create oai document Document oai = builder.newDocument(); // set document version oai.setXmlVersion("1.0"); oai.setXmlStandalone(true); // create root OAI-PMH element Element oaiPmh = oai.createElement("OAI-PMH"); // set document namespaces oaiPmh.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/"); oaiPmh.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); oaiPmh.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd"); // append root node oai.appendChild(oaiPmh); // create responseDate element Element responseDate = oai.createElement("responseDate"); // create simple date format DateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT); // generate date String date = dateFormat.format(new Date()); // set current date and time responseDate.setTextContent(date); oaiPmh.appendChild(responseDate); Element listRecords = oai.createElement("ListRecords"); oaiPmh.appendChild(listRecords); // create xpath factory XPathFactory xPathfactory = XPathFactory.newInstance(); // create namespace context NamespaceContext namespaceContext = new NamespaceContext() { public String getNamespaceURI(String prefix) { if (prefix.equals("rdf")) return RDF_NAMESPACE; else if (prefix.equals("rns")) return RNF_NAMESPACE; else return null; } @Override public Iterator<?> getPrefixes(String val) { throw new IllegalAccessError("Not implemented!"); } @Override public String getPrefix(String uri) { throw new IllegalAccessError("Not implemented!"); } }; // create xpath object XPath xpath = xPathfactory.newXPath(); // set namespace contex xpath.setNamespaceContext(namespaceContext); // create XPath expressions XPathExpression idExpr = xpath.compile("/rdf:RDF/rns:Researcher/@rdf:about"); XPathExpression emptyExpr = xpath.compile("//text()[normalize-space(.) = '']"); // create RegEx patterns Pattern pattern = Pattern.compile( "<\\?xml\\s+version=\"[\\d\\.]+\"\\s*\\?>\\s*<\\s*rdf:RDF[^>]*>[\\s\\S]*?<\\s*\\/\\s*rdf:RDF\\s*>"); // read file into a string String content = new String(Files.readAllBytes(source), inputEncoding); Matcher matcher = pattern.matcher(content); // process all records while (matcher.find()) { // convert string to input stream ByteArrayInputStream input = new ByteArrayInputStream( matcher.group().getBytes(StandardCharsets.UTF_8.toString())); // parse the xml document Document doc = builder.parse(input); // remove all spaces NodeList emptyNodes = (NodeList) emptyExpr.evaluate(doc, XPathConstants.NODESET); // Remove each empty text node from document. for (int i = 0; i < emptyNodes.getLength(); i++) { Node emptyTextNode = emptyNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } // obtain researcher id String id = (String) idExpr.evaluate(doc, XPathConstants.STRING); if (StringUtils.isEmpty(id)) throw new Exception("The record identifier can not be empty"); // create record element Element record = oai.createElement("record"); listRecords.appendChild(record); // create header element Element header = oai.createElement("header"); record.appendChild(header); // create identifier element Element identifier = oai.createElement("identifier"); identifier.setTextContent(id); header.appendChild(identifier); // create datestamp element Element datestamp = oai.createElement("datestamp"); datestamp.setTextContent(date); header.appendChild(datestamp); // create set spec element if it exists if (!StringUtils.isEmpty(setSpecName)) { Element setSpec = oai.createElement("setSpec"); setSpec.setTextContent(setSpecName); header.appendChild(setSpec); } // create metadata element Element metadata = oai.createElement("metadata"); record.appendChild(metadata); // import the record metadata.appendChild(oai.importNode(doc.getDocumentElement(), true)); } // create transformer factory TransformerFactory transformerFactory = TransformerFactory.newInstance(); // create transformer Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); if (formatOutput) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } else transformer.setOutputProperty(OutputKeys.INDENT, "no"); // create dom source DOMSource oaiSource = new DOMSource(oai); // create stream result StreamResult result = new StreamResult(target.toFile()); // stream xml to file transformer.transform(oaiSource, result); // optional stream xml to console for testing //StreamResult consoleResult = new StreamResult(System.out); //transformer.transform(oaiSource, consoleResult); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); //e.printStackTrace(); System.exit(1); } }
From source file:org.soaplab.services.Config.java
/************************************************************************** * Get all properties contained in the configuration whose keys * (names) match the specified prefix. <p> * * The remaining parameters are used in the similar way as in * {@link #getString getString} method. Meaning if they are not * null, the following prefixes are actually tried: * *<pre>//ww w. j a v a 2 s . c om * <prefix>. * <class-of-owner>.<prefix>. * <serviceName>.<prefix>. *</pre> * * These prefixes are tried in the order as indicated above - * causing the properties with earlier prefixes being overwritten * by those having newer ones. For example, having the following * properties in the configuration (<tt>classic.helloworld</tt> is * a name of a service): * *<pre> * classic.helloworld.grid.env.One = ein * classic.helloworld.grid.env.Two = zwei * grid.env.One = un * grid.env.Two = deux * grid.env.Three = trois *</pre> * * and calling: * *<pre> * getMatchingProperties ("grid.env", "classic.helloworld", null) *</pre> * * will return properties: * *<pre> * One = ein * Two = zwei * Three = troi *</pre> * * @param prefix is a part of property name (may or may not end * with a dot) * * @param serviceName is a possibly 'prefix' for the 'prefix' (can * be null) * * @param owner is another possible 'prefix' for the 'prefix': if * 'owner' is of type Class its name is used, otherwise, the name * of the class of the instance 'owner' is used * * @return properties matching the prefix - the prefix is not part * of the returned property names; if nothing matches, an empty * list is returned (not null) **************************************************************************/ public static Properties getMatchingProperties(String prefix, String serviceName, Object owner) { Properties props = new Properties(); if (prefix.endsWith(".")) prefix = prefix.substring(0, prefix.length() - 1); // try with a pure prefix int prefixLen = prefix.length() + 1; // 1 is for ending dor CompositeConfiguration cfg = get(); synchronized (cfg) { for (Iterator it = cfg.getKeys(prefix); it.hasNext();) { String key = (String) it.next(); props.put(key.substring(prefixLen), cfg.getString(key)); } } String extendedPrefix = null; // try with an owner class and prefix if (owner != null) { extendedPrefix = (owner instanceof Class ? ((Class) owner).getName() : owner.getClass().getName()) + "." + prefix; prefixLen = extendedPrefix.length() + 1; synchronized (cfg) { for (Iterator it = cfg.getKeys(extendedPrefix); it.hasNext();) { String key = (String) it.next(); props.put(key.substring(prefixLen), cfg.getString(key)); } } } // try with a service name and prefix if (serviceName != null) { extendedPrefix = serviceName + "." + prefix; prefixLen = extendedPrefix.length() + 1; synchronized (cfg) { for (Iterator it = cfg.getKeys(extendedPrefix); it.hasNext();) { String key = (String) it.next(); props.put(key.substring(prefixLen), cfg.getString(key)); } } } return props; }
From source file:org.waveprotocol.wave.util.settings.SettingsBinder.java
/** * Bind configuration parameters into Guice Module. * * @return a Guice module configured with setting support. * @throws ConfigurationException on configuration error *///from ww w . j a v a 2 s .c o m public static Module bindSettings(String propertiesFileKey, Class<?>... settingsArg) throws ConfigurationException { final CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); String propertyFile = config.getString(propertiesFileKey); if (propertyFile != null) { config.addConfiguration(new PropertiesConfiguration(propertyFile)); } List<Field> fields = new ArrayList<Field>(); for (Class<?> settings : settingsArg) { fields.addAll(Arrays.asList(settings.getDeclaredFields())); } // Reflect on settings class and absorb settings final Map<Setting, Field> settings = new LinkedHashMap<Setting, Field>(); for (Field field : fields) { if (!field.isAnnotationPresent(Setting.class)) { continue; } // Validate target type SettingTypeValidator typeHelper = supportedSettingTypes.get(field.getType()); if (typeHelper == null || !typeHelper.check(field.getGenericType())) { throw new IllegalArgumentException(field.getType() + " is not one of the supported setting types"); } Setting setting = field.getAnnotation(Setting.class); settings.put(setting, field); } // Now validate them List<String> missingProperties = new ArrayList<String>(); for (Setting setting : settings.keySet()) { if (setting.defaultValue().isEmpty()) { if (!config.containsKey(setting.name())) { missingProperties.add(setting.name()); } } } if (missingProperties.size() > 0) { StringBuilder error = new StringBuilder(); error.append("The following required properties are missing from the server configuration: "); error.append(Joiner.on(", ").join(missingProperties)); throw new ConfigurationException(error.toString()); } // bundle everything up in an injectable guice module return new AbstractModule() { @Override protected void configure() { // We must iterate the settings a third time when binding. // Note: do not collapse these loops as that will damage // early error detection. The runtime is still O(n) in setting count. for (Map.Entry<Setting, Field> entry : settings.entrySet()) { Class<?> type = entry.getValue().getType(); Setting setting = entry.getKey(); if (int.class.equals(type)) { Integer defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Integer.parseInt(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getInteger(setting.name(), defaultValue)); } else if (boolean.class.equals(type)) { Boolean defaultValue = null; if (!setting.defaultValue().isEmpty()) { defaultValue = Boolean.parseBoolean(setting.defaultValue()); } bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getBoolean(setting.name(), defaultValue)); } else if (String.class.equals(type)) { bindConstant().annotatedWith(Names.named(setting.name())) .to(config.getString(setting.name(), setting.defaultValue())); } else { String[] value = config.getStringArray(setting.name()); if (value.length == 0 && !setting.defaultValue().isEmpty()) { value = setting.defaultValue().split(","); } bind(new TypeLiteral<List<String>>() { }).annotatedWith(Names.named(setting.name())).toInstance(ImmutableList.copyOf(value)); } } } }; }
From source file:org.xwiki.rendering.test.cts.TestDataParser.java
/** * Parse Test configuration by looking for a {@code config.properties} file in the Syntax directory. * * @param syntaxDirectory the syntax directory under which to look for the configuration file * @param ctsRootPackageName the root of the CTS resources * @param classLoader the class loader from which the test configuration is read from * @return the configuration/*w w w . j a v a 2s . c o m*/ * @throws Exception in case of error while reading test configuration */ public TestDataConfiguration parseTestConfiguration(String syntaxDirectory, String ctsRootPackageName, ClassLoader classLoader) throws Exception { TestDataConfiguration configuration = new TestDataConfiguration(); CompositeConfiguration compositeConfiguration = new CompositeConfiguration(); addConfigurationData(compositeConfiguration, ctsRootPackageName, classLoader); addConfigurationData(compositeConfiguration, syntaxDirectory, classLoader); // TODO: Remove these unsafe casts, need to find out how to do that nicely... configuration.notApplicableTests = (List<String>) (List<?>) compositeConfiguration .getList("notApplicableTests", Collections.emptyList()); configuration.failingTests = (List<String>) (List<?>) compositeConfiguration.getList("failingTests", Collections.emptyList()); configuration.testDescriptions = compositeConfiguration.getProperties("testDescriptions", new Properties()); configuration.inheritSyntax = compositeConfiguration.getString("inheritSyntax"); return configuration; }
From source file:uk.co.gidley.jmxmonitor.monitoring.MonitoringGroup.java
/** * Initialise the monitor. If possible we start the JMX connection now. If not we create a placeholder. * * @param monitorUrlKey/*from ww w . j av a 2s. c om*/ * @param monitorsConfiguration * @throws MalformedObjectNameException * @throws MalformedURLException */ private void initialiseMonitorUrl(String monitorUrlKey, CompositeConfiguration monitorsConfiguration) throws MalformedObjectNameException, MalformedURLException { logger.debug("Initialising Monitor Connection {}", monitorUrlKey); String url = monitorsConfiguration.getString(ThreadManager.PROPERTY_PREFIX + monitorUrlKey + URL); try { // Create JMX connection JMXServiceURL serviceUrl = new JMXServiceURL(url); JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null); logger.debug("JMX connection made {}", jmxc); MonitoringGroup.MonitorUrlHolder monitorUrlHolder = monitorUrlHolders.get(monitorUrlKey); monitorUrlHolder.setmBeanServerConnection(jmxc.getMBeanServerConnection()); monitorUrlHolder.getMonitors().clear(); // Parse monitors inside this List<String> loadedMonitors = new ArrayList<String>(); Iterator<String> monitorKeys = monitorsConfiguration .getKeys(ThreadManager.PROPERTY_PREFIX + monitorUrlKey); while (monitorKeys.hasNext()) { String key = monitorKeys.next(); if (!key.endsWith(URL)) { String monitorName = key.substring( ThreadManager.PROPERTY_PREFIX.length() + monitorUrlKey.length() + 1, key.lastIndexOf(".")); // Only load each on once (there will be n keys) if (!loadedMonitors.contains(monitorName)) { constructMonitor(monitorUrlKey, monitorsConfiguration, monitorUrlHolder, monitorName); loadedMonitors.add(monitorName); } } } } catch (IOException e) { if (e instanceof MalformedURLException) { throw (MalformedURLException) e; } logger.warn("Unable to connect to {}, {}", monitorUrlKey, e); } }
From source file:uk.co.gidley.jmxmonitor.monitoring.MonitoringGroup.java
private void constructMonitor(String monitorUrlKey, CompositeConfiguration monitorsConfiguration, MonitorUrlHolder monitorUrlHolder, String monitorName) throws MalformedObjectNameException { // Value of key is java.lang:type=Memory/HeapMemoryUsage!Heap String keyPrefix = ThreadManager.PROPERTY_PREFIX + monitorUrlKey + "." + monitorName; String objectName = monitorsConfiguration.getString(keyPrefix + ".objectName"); String attribute = monitorsConfiguration.getString(keyPrefix + ".attribute"); String discriminator = monitorsConfiguration.getString(keyPrefix + ".discriminator", null); Monitor monitor;//from w ww .ja v a 2s . c om if (discriminator == null) { monitor = new SimpleJmxMonitor(monitorName, new ObjectName(objectName), attribute, monitorUrlHolder.getmBeanServerConnection()); } else { monitor = new DiscriminatingJmxMonitor(monitorName, new ObjectName(objectName), attribute, discriminator, monitorUrlHolder.getmBeanServerConnection()); } monitorUrlHolder.getMonitors().add(monitor); }