List of usage examples for java.util Properties get
@Override
public Object get(Object key)
From source file:com.impetus.client.redis.RedisClientFactory.java
@Override protected Object createPoolOrConnection() { logger.info("Initializing Redis connection pool"); final byte WHEN_EXHAUSTED_FAIL = 0; PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata() .getPersistenceUnitMetadata(getPersistenceUnit()); Properties props = puMetadata.getProperties(); String contactNode = null;/*from www . j a v a2 s . c om*/ String defaultPort = null; String password = null; String maxActivePerNode = null; String maxIdlePerNode = null; String minIdlePerNode = null; String maxTotal = null; String txTimeOut = null; if (externalProperties != null) { contactNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES); defaultPort = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT); password = (String) externalProperties.get(PersistenceProperties.KUNDERA_PASSWORD); maxActivePerNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE); maxIdlePerNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_IDLE); minIdlePerNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MIN_IDLE); maxTotal = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_TOTAL); txTimeOut = (String) externalProperties.get(PersistenceProperties.KUNDERA_TRANSACTION_TIMEOUT); } if (contactNode == null) { contactNode = RedisPropertyReader.rsmd.getHost() != null ? RedisPropertyReader.rsmd.getHost() : (String) props.get(PersistenceProperties.KUNDERA_NODES); } if (defaultPort == null) { defaultPort = RedisPropertyReader.rsmd.getPort() != null ? RedisPropertyReader.rsmd.getPort() : (String) props.get(PersistenceProperties.KUNDERA_PORT); } if (password == null) { password = RedisPropertyReader.rsmd.getPassword() != null ? RedisPropertyReader.rsmd.getPassword() : (String) props.get(PersistenceProperties.KUNDERA_PASSWORD); } if (maxActivePerNode == null) { maxActivePerNode = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE); } if (maxIdlePerNode == null) { maxIdlePerNode = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_IDLE); } if (minIdlePerNode == null) { minIdlePerNode = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MIN_IDLE); } if (maxTotal == null) { maxTotal = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_TOTAL); } if (txTimeOut == null) { txTimeOut = props.getProperty(PersistenceProperties.KUNDERA_TRANSACTION_TIMEOUT); } JedisPoolConfig poolConfig = onPoolConfig(WHEN_EXHAUSTED_FAIL, maxActivePerNode, maxIdlePerNode, minIdlePerNode, maxTotal); JedisPool pool = null; onValidation(contactNode, defaultPort); if (poolConfig != null) { if (password != null) { pool = new JedisPool(poolConfig, contactNode, Integer.parseInt(defaultPort), txTimeOut != null && StringUtils.isNumeric(txTimeOut) ? Integer.parseInt(txTimeOut) : -1, password); } else { pool = new JedisPool(poolConfig, contactNode, Integer.parseInt(defaultPort), txTimeOut != null && StringUtils.isNumeric(txTimeOut) ? Integer.parseInt(txTimeOut) : -1); } return pool; } else { // Jedis connection = new Jedis(contactNode, // Integer.valueOf(defaultPort)); // if (password != null) // { // // connection.auth(password); // } // connection.connect(); // Connection to made available at the time of getConnection(). YCSB // performance fixes and ideally it is needed at that time only. // No need to cache it at factory level as needed to managed within // entity manager boundary! return null; } }
From source file:com.cloud.consoleproxy.ConsoleProxy.java
public static void startWithContext(Properties conf, Object context, byte[] ksBits, String ksPassword) { s_logger.info("Start console proxy with context"); if (conf != null) { for (Object key : conf.keySet()) { s_logger.info("Context property " + (String) key + ": " + conf.getProperty((String) key)); }/*from ww w .j a va2 s . c o m*/ } configLog4j(); Logger.setFactory(new ConsoleProxyLoggerFactory()); // Using reflection to setup private/secure communication channel towards management server ConsoleProxy.context = context; ConsoleProxy.ksBits = ksBits; ConsoleProxy.ksPassword = ksPassword; try { Class<?> contextClazz = Class.forName("com.cloud.agent.resource.consoleproxy.ConsoleProxyResource"); authMethod = contextClazz.getDeclaredMethod("authenticateConsoleAccess", String.class, String.class, String.class, String.class, String.class, Boolean.class); reportMethod = contextClazz.getDeclaredMethod("reportLoadInfo", String.class); ensureRouteMethod = contextClazz.getDeclaredMethod("ensureRoute", String.class); } catch (SecurityException e) { s_logger.error("Unable to setup private channel due to SecurityException", e); } catch (NoSuchMethodException e) { s_logger.error("Unable to setup private channel due to NoSuchMethodException", e); } catch (IllegalArgumentException e) { s_logger.error("Unable to setup private channel due to IllegalArgumentException", e); } catch (ClassNotFoundException e) { s_logger.error("Unable to setup private channel due to ClassNotFoundException", e); } // merge properties from conf file InputStream confs = ConsoleProxy.class.getResourceAsStream("/conf/consoleproxy.properties"); Properties props = new Properties(); if (confs == null) { s_logger.info("Can't load consoleproxy.properties from classpath, will use default configuration"); } else { try { props.load(confs); for (Object key : props.keySet()) { // give properties passed via context high priority, treat properties from consoleproxy.properties // as default values if (conf.get(key) == null) conf.put(key, props.get(key)); } } catch (Exception e) { s_logger.error(e.toString(), e); } } start(conf); }
From source file:br.org.indt.ndg.client.Service.java
public Collection<PreferenceVO> listPreferences() throws NDGServerException { try {/*from ww w.j a v a 2 s . co m*/ MSMBusinessDelegate msmBD = new MSMBusinessDelegate(); Properties p = msmBD.getSettings(); //Get Hashtable Enumeration to get key and value Enumeration keyEnum = p.keys(); ArrayList<PreferenceVO> list = new ArrayList<PreferenceVO>(); while (keyEnum.hasMoreElements()) { //nextElement is used to get key of hashtable String key = (String) keyEnum.nextElement(); //get is used to get value of key in hashtable String value = (String) p.get(key); PreferenceVO bean = new PreferenceVO(); bean.setPreference(key); bean.setValue(value); list.add(bean); } return list; } catch (MSMApplicationException e) { e.printStackTrace(); throw new NDGServerException(e.getErrorCode()); } }
From source file:org.canova.api.conf.Configuration.java
/** * Write out the non-default properties in this configuration to the give * {@link OutputStream}.// ww w . j a v a 2 s.c o m * * @param out the output stream to write to. */ public void writeXml(OutputStream out) throws IOException { Properties properties = getProps(); try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element conf = doc.createElement("configuration"); doc.appendChild(conf); conf.appendChild(doc.createTextNode("\n")); for (Enumeration e = properties.keys(); e.hasMoreElements();) { String name = (String) e.nextElement(); Object object = properties.get(name); String value; if (object instanceof String) { value = (String) object; } else { continue; } Element propNode = doc.createElement("property"); conf.appendChild(propNode); Element nameNode = doc.createElement("name"); nameNode.appendChild(doc.createTextNode(name)); propNode.appendChild(nameNode); Element valueNode = doc.createElement("value"); valueNode.appendChild(doc.createTextNode(value)); propNode.appendChild(valueNode); conf.appendChild(doc.createTextNode("\n")); } DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:info.magnolia.importexport.PropertiesImportExport.java
/** * Transforms the keys to the following inner notation: <code>some/path/node.prop</code> or <code>some/path/node.@type</code>. *///from w w w .j a v a 2 s. c o m private Properties keysToInnerFormat(Properties properties) { Properties cleaned = new OrderedProperties(); for (Object o : properties.keySet()) { String orgKey = (String) o; //if this is a node definition (no property) String newKey = orgKey; // make sure we have a dot as a property separator newKey = StringUtils.replace(newKey, "@", ".@"); // avoid double dots newKey = StringUtils.replace(newKey, "..@", ".@"); String propertyName = StringUtils.substringAfterLast(newKey, "."); String keySuffix = StringUtils.substringBeforeLast(newKey, "."); String path = StringUtils.replace(keySuffix, ".", "/"); path = StringUtils.removeStart(path, "/"); // if this is a path (no property) if (StringUtils.isEmpty(propertyName)) { // no value --> is a node if (StringUtils.isEmpty(properties.getProperty(orgKey))) { // make this the type property if not defined otherwise if (!properties.containsKey(orgKey + "@type")) { cleaned.put(path + ".@type", ItemType.CONTENTNODE.getSystemName()); } continue; } propertyName = StringUtils.substringAfterLast(path, "/"); path = StringUtils.substringBeforeLast(path, "/"); } cleaned.put(path + "." + propertyName, properties.get(orgKey)); } return cleaned; }
From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java
/** * Auto generated method comment//from w w w . j a v a 2 s. c o m * * @return */ private String[] getConnectionProperties() { Properties props = Context.getRuntimeProperties(); // username, password, database, host, port String[] connProps = { "test", "test", "openmrs", "localhost", "3306" }; String username = (String) props.get("database.username"); if (username == null) username = (String) props.get("connection.username"); if (username != null) connProps[0] = username; String password = (String) props.get("database.password"); if (password == null) password = (String) props.get("connection.password"); if (password != null) connProps[1] = password; // get database name String database = "openmrs"; String host = "localhost"; String port = "3306"; String connectionUrl = (String) props.get("connection.url"); if (connectionUrl == null) connectionUrl = (String) props.get("connection.url"); if (connectionUrl != null) { //jdbc:mysql://localhost:3306/openmrs //jdbc:mysql:mxj://127.0.0.1:3317/openmrs? //Assuming the last full colon will be that before the port int lastColonPos = connectionUrl.lastIndexOf(':'); int slash = connectionUrl.indexOf('/', lastColonPos); int qmark = connectionUrl.indexOf('?', lastColonPos); database = connectionUrl.substring(slash + 1, qmark != -1 ? qmark : connectionUrl.length()); connProps[2] = database; //Assuming that port is explicitly set int doubleSlashPos = connectionUrl.indexOf("://"); host = connectionUrl.substring(doubleSlashPos + 3, lastColonPos); connProps[3] = host; port = connectionUrl.substring(lastColonPos + 1, slash); connProps[4] = port; } return connProps; }
From source file:net.jetrix.config.ServerConfig.java
/** * Save the configuration./*from w w w . j a v a 2 s .c o m*/ */ public void save() throws IOException { // todo make a backup copy of the previous configuration files // save the server.xml file PrintWriter out = null; try { File file = new File(serverConfigURL.toURI()); out = new PrintWriter(file, ENCODING); } catch (URISyntaxException e) { log.log(Level.SEVERE, e.getMessage(), e); } out.println("<?xml version=\"1.0\"?>"); out.println( "<!DOCTYPE tetrinet-server PUBLIC \"-//LFJR//Jetrix TetriNET Server//EN\" \"http://jetrix.sourceforge.net/dtd/tetrinet-server.dtd\">"); out.println(); out.println("<tetrinet-server host=\"" + (host == null ? "[ALL]" : host.getHostAddress()) + "\">"); out.println(); out.println(" <!-- Server name -->"); out.println(" <name>" + getName() + "</name>"); out.println(); out.println(" <!-- Server default language (using an ISO-639 two-letter language code) -->"); out.println(" <language>" + getLocale().getLanguage() + "</language>"); out.println(); out.println(" <!-- How many seconds of inactivity before timeout occurs -->"); out.println(" <timeout>" + getTimeout() + "</timeout>"); out.println(); out.println(" <!-- How many channels should be available on the server -->"); out.println(" <max-channels>" + getMaxChannels() + "</max-channels>"); out.println(); out.println(" <!-- Maximum number of players on the server -->"); out.println(" <max-players>" + getMaxPlayers() + "</max-players>"); out.println(); out.println(" <!-- Maximum number of simultaneous connections allowed from the same IP -->"); out.println(" <max-connections>" + getMaxConnections() + "</max-connections>"); out.println(); out.println(" <!-- Typing /op <thispassword> will give player operator status -->"); out.println(" <op-password>" + getOpPassword() + "</op-password>"); out.println(); out.println(" <!-- Use this password to log on the administration console -->"); out.println(" <admin-password>" + getAdminPassword() + "</admin-password>"); out.println(); out.println(" <!-- Access Log, where requests are logged to -->"); out.println(" <access-log path=\"" + getAccessLogPath() + "\" />"); out.println(); out.println(" <!-- Error Log, where errors are logged to -->"); out.println(" <error-log path=\"" + getErrorLogPath() + "\" />"); out.println(); out.println(" <!-- Path to the channels descriptor file (relative to the current configuration file) -->"); out.println(" <channels path=\"" + getChannelsFile() + "\"/>"); out.println(); out.println(" <!-- Client listeners -->"); out.println(" <listeners>"); for (Listener listener : getListeners()) { String autostart = !listener.isAutoStart() ? " auto-start=\"false\"" : ""; out.println(" <listener class=\"" + listener.getClass().getName() + "\" port=\"" + listener.getPort() + "\"" + autostart + "/>"); } out.println(" </listeners>"); out.println(); out.println(" <!-- Services -->"); out.println(" <services>"); for (Service service : getServices()) { try { // get the parameters Map<String, Object> params = PropertyUtils.describe(service); String autostart = !service.isAutoStart() ? "auto-start=\"false\"" : ""; String classname = "class=\"" + service.getClass().getName() + "\""; if (params.size() <= 4) { out.println(" <service " + classname + " " + autostart + "/>"); } else { out.println(" <service " + classname + " " + autostart + ">"); for (String param : params.keySet()) { PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(service, param); if (!"autoStart".equals(param) && desc.getWriteMethod() != null) { out.println( " <param name=\"" + param + "\" value=\"" + params.get(param) + "\"/>"); } } out.println(" </service>"); } } catch (Exception e) { e.printStackTrace(); } } out.println(" </services>"); out.println(); out.println(" <!-- Server commands -->"); out.println(" <commands>"); Iterator<Command> commands = CommandManager.getInstance().getCommands(AccessLevel.ADMINISTRATOR); while (commands.hasNext()) { try { Command command = commands.next(); String hidden = command.isHidden() ? " hidden=\"true\"" : ""; Command command2 = command.getClass().newInstance(); String level = command2.getAccessLevel() != command.getAccessLevel() ? " access-level=\"" + command.getAccessLevel() + "\"" : ""; out.println(" <command class=\"" + command.getClass().getName() + "\"" + hidden + level + "/>"); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); } } out.println(" </commands>"); out.println(); out.println(" <ban>"); Iterator<Banlist.Entry> entries = Banlist.getInstance().getBanlist(); while (entries.hasNext()) { Banlist.Entry entry = entries.next(); out.println(" <host>" + entry.pattern + "</host>"); } out.println(" </ban>"); out.println(); if (!datasources.isEmpty()) { out.println(" <!-- Database connection parameters -->"); out.println(" <datasources>"); out.println(); for (DataSourceConfig datasource : datasources.values()) { out.println(" <datasource name=\"" + datasource.getName() + "\">"); out.println(" <!-- The class of the JDBC driver used -->"); out.println(" <driver>" + datasource.getDriver() + "</driver>"); out.println(); out.println(" <!-- The URL of the database (jdbc:<type>://<hostname>:<port>/<database>) -->"); out.println(" <url>" + datasource.getUrl() + "</url>"); out.println(); out.println(" <!-- The username connecting to the database -->"); out.println(" <username>" + datasource.getUsername() + "</username>"); out.println(); out.println(" <!-- The password of the user -->"); if (datasource.getPassword() != null) { out.println(" <password>" + datasource.getPassword() + "</password>"); } else { out.println(" <password/>"); } if (datasource.getMinIdle() != DataSourceManager.DEFAULT_MIN_IDLE) { out.println(); out.println(" <!-- The minimum number of idle connections -->"); out.println(" <min-idle>" + datasource.getMinIdle() + "</min-idle>"); } if (datasource.getMaxActive() != DataSourceManager.DEFAULT_MAX_ACTIVE) { out.println(); out.println(" <!-- The maximum number of active connections -->"); out.println(" <max-active>" + datasource.getMaxActive() + "</max-active>"); } out.println(" </datasource>"); out.println(); } out.println(" </datasources>"); out.println(); } if (mailSessionConfig != null) { StringBuilder buffer = new StringBuilder(); buffer.append(" <mailserver host=\"").append(mailSessionConfig.getHostname()).append("\""); buffer.append(" port=\"").append(mailSessionConfig.getPort()).append("\""); if (mailSessionConfig.isAuth()) { buffer.append(" auth=\"true\""); buffer.append(" username=\"").append(mailSessionConfig.getUsername()).append("\""); buffer.append(" password=\"").append(mailSessionConfig.getPassword()).append("\""); } if (mailSessionConfig.isDebug()) { buffer.append(" debug=\"true\""); } buffer.append("/>"); out.println(" <!-- Mail server parameters -->"); out.println(buffer.toString()); out.println(); } if (properties != null && !properties.isEmpty()) { out.println(" <!-- Extended properties -->"); out.println(" <properties>"); for (String key : properties.stringPropertyNames()) { out.println(" <property name=\"" + key + "\" value=\"" + properties.getProperty(key) + "\">"); } out.println(" </properties>"); out.println(); } out.println("</tetrinet-server>"); out.flush(); out.close(); // save the channels.xml file try { File file = new File(channelsConfigURL.toURI()); out = new PrintWriter(file, ENCODING); } catch (URISyntaxException e) { log.log(Level.SEVERE, e.getMessage(), e); } out.println("<?xml version=\"1.0\"?>"); out.println( "<!DOCTYPE tetrinet-channels PUBLIC \"-//LFJR//Jetrix Channels//EN\" \"http://jetrix.sourceforge.net/dtd/tetrinet-channels.dtd\">"); out.println(); out.println("<tetrinet-channels>"); out.println(); out.println(" <!-- Message Of The Day -->"); out.println(" <motd><![CDATA["); out.println(getMessageOfTheDay()); out.println(" ]]></motd>"); out.println(); // filter definitions Map<String, String> aliases = FilterManager.getInstance().getFilterAliases(); out.println(" <!-- Channel filters -->"); out.println(" <filter-definitions>"); for (String alias : aliases.keySet()) { out.println(" <alias name=\"" + alias + "\" class=\"" + aliases.get(alias) + "\"/>"); } out.println(" </filter-definitions>"); out.println(); // global filters out.println(" <!-- Global filters -->"); out.println(" <default-filters>"); for (FilterConfig filter : globalFilters) { saveFilter(filter, out, " "); } out.println(" </default-filters>"); out.println(); // winlists out.println(" <!-- Winlists -->"); out.println(" <winlists>"); for (Winlist winlist : WinlistManager.getInstance().getWinlists()) { WinlistConfig config = winlist.getConfig(); Properties props = config.getProperties(); if (props == null || props.isEmpty()) { out.println(" <winlist name=\"" + winlist.getId() + "\" class=\"" + winlist.getClass().getName() + "\"/>"); } else { out.println(" <winlist name=\"" + winlist.getId() + "\" class=\"" + winlist.getClass().getName() + "\">"); for (Object name : props.keySet()) { out.println(" <param name=\"" + name + "\" value=\"" + props.get(name) + "\"/>"); } out.println(" </winlist>"); } } out.println(" </winlists>"); out.println(); // default settings Settings settings = Settings.getDefaultSettings(); out.println(" <!-- Default game settings -->"); out.println(" <default-settings>"); out.println(" <!-- What level each player starts at -->"); out.println(" <starting-level>" + settings.getStartingLevel() + "</starting-level>"); out.println(); out.println(" <!-- How many lines to make before player level increases -->"); out.println(" <lines-per-level>" + settings.getLinesPerLevel() + "</lines-per-level>"); out.println(); out.println(" <!-- Number of levels to increase each time -->"); out.println(" <level-increase>" + settings.getLevelIncrease() + "</level-increase>"); out.println(); out.println(" <!-- Lines to make to get a special block -->"); out.println(" <lines-per-special>" + settings.getLinesPerSpecial() + "</lines-per-special>"); out.println(); out.println(" <!-- Number of special blocks added each time -->"); out.println(" <special-added>" + settings.getSpecialAdded() + "</special-added>"); out.println(); out.println(" <!-- Capacity of Special block inventory -->"); out.println(" <special-capacity>" + settings.getSpecialCapacity() + "</special-capacity>"); out.println(); out.println(" <!-- Play by classic rules? -->"); out.println(" <classic-rules>" + (settings.getClassicRules() ? "true" : "false") + "</classic-rules>"); out.println(); out.println(" <!-- Average together all player's game level? -->"); out.println( " <average-levels>" + (settings.getAverageLevels() ? "true" : "false") + "</average-levels>"); out.println(); out.println(" <!-- Same sequence of blocks for all players? (tetrinet 1.14 clients only) -->"); out.println(" <same-blocks>" + (settings.getSameBlocks() ? "true" : "false") + "</same-blocks>"); out.println(); out.println(" <block-occurancy>"); for (Block block : Block.values()) { out.println(" <" + block.getCode() + ">" + settings.getOccurancy(block) + "</" + block.getCode() + ">"); } out.println(" </block-occurancy>"); out.println(); out.println(" <special-occurancy>"); for (Special special : Special.values()) { out.println(" <" + special.getCode() + ">" + settings.getOccurancy(special) + "</" + special.getCode() + ">"); } out.println(" </special-occurancy>"); out.println(); out.println(" <!-- Sudden death parameters -->"); out.println(" <sudden-death>"); out.println(" <!-- Time in seconds before the sudden death begins, 0 to disable the sudden death -->"); out.println(" <time>" + settings.getSuddenDeathTime() + "</time>"); out.println(); out.println( " <!-- The message displayed when the sudden death begins. Use \"key:\" prefix to display an internationalized message -->"); out.println(" <message>" + settings.getSuddenDeathMessage() + "</message>"); out.println(); out.println(" <!-- The delay in seconds between lines additions -->"); out.println(" <delay>" + settings.getSuddenDeathDelay() + "</delay>"); out.println(); out.println(" <!-- The number of lines added -->"); out.println(" <lines-added>" + settings.getSuddenDeathLinesAdded() + "</lines-added>"); out.println(" </sudden-death>"); out.println(); out.println(" </default-settings>"); out.println(); out.println(); out.println(" <channels>"); for (Channel channel : ChannelManager.getInstance().channels()) { ChannelConfig config = channel.getConfig(); if (config.isPersistent()) { out.println(" <channel name=\"" + config.getName() + "\">"); if (config.getDescription() != null) { String description = config.getDescription(); description = description.contains("<") ? "<![CDATA[" + description + "]]>" : description; out.println(" <description>" + description + "</description>"); } if (config.getTopic() != null && config.getTopic().trim().length() > 0) { out.println(" <topic>"); out.println("<![CDATA["); out.println(config.getTopic()); out.println("]]>"); out.println(" </topic>"); } if (config.getSpeed() != Speed.MIXED) { out.println(" <speed>" + config.getSpeed().name().toLowerCase() + "</speed>"); } if (config.isPasswordProtected()) { out.println(" <password>" + config.getPassword() + "</password>"); } if (config.getAccessLevel() != AccessLevel.PLAYER) { out.println(" <access-level>" + config.getAccessLevel() + "</access-level>"); } if (config.isIdleAllowed()) { out.println(" <idle>true</idle>"); } if (!config.isVisible()) { out.println(" <visible>false</visible>"); } if (config.getMaxPlayers() != ChannelConfig.PLAYER_CAPACITY) { out.println(" <max-players>" + config.getMaxPlayers() + "</max-players>"); } if (config.getMaxSpectators() != ChannelConfig.SPECTATOR_CAPACITY) { out.println(" <max-spectators>" + config.getMaxSpectators() + "</max-spectators>"); } if (config.getWinlistId() != null) { out.println(" <winlist name=\"" + config.getWinlistId() + "\"/>"); } // channel settings settings = config.getSettings(); if (!settings.useDefaultSettings()) { out.println(" <settings>"); if (!settings.isDefaultStartingLevel()) { out.println(" <starting-level>" + settings.getStartingLevel() + "</starting-level>"); } if (!settings.isDefaultLinesPerLevel()) { out.println( " <lines-per-level>" + settings.getLinesPerLevel() + "</lines-per-level>"); } if (!settings.isDefaultLevelIncrease()) { out.println(" <level-increase>" + settings.getLevelIncrease() + "</level-increase>"); } if (!settings.isDefaultLinesPerSpecial()) { out.println(" <lines-per-special>" + settings.getLinesPerSpecial() + "</lines-per-special>"); } if (!settings.isDefaultSpecialAdded()) { out.println(" <special-added>" + settings.getSpecialAdded() + "</special-added>"); } if (!settings.isDefaultSpecialCapacity()) { out.println(" <special-capacity>" + settings.getSpecialCapacity() + "</special-capacity>"); } if (!settings.isDefaultClassicRules()) { out.println(" <classic-rules>" + (settings.getClassicRules() ? "true" : "false") + "</classic-rules>"); } if (!settings.isDefaultAverageLevels()) { out.println(" <average-levels>" + (settings.getAverageLevels() ? "true" : "false") + "</average-levels>"); } if (!settings.isDefaultSameBlocks()) { out.println(" <same-blocks>" + (settings.getSameBlocks() ? "true" : "false") + "</same-blocks>"); } if (!settings.isDefaultBlockOccurancy()) { out.println(" <block-occurancy>"); for (Block block : Block.values()) { if (settings.getOccurancy(block) != 0) { out.println(" <" + block.getCode() + ">" + settings.getOccurancy(block) + "</" + block.getCode() + ">"); } } out.println(" </block-occurancy>"); } if (!settings.isDefaultSpecialOccurancy()) { out.println(" <special-occurancy>"); for (Special special : Special.values()) { if (settings.getOccurancy(special) != 0) { out.println(" <" + special.getCode() + ">" + settings.getOccurancy(special) + "</" + special.getCode() + ">"); } } out.println(" </special-occurancy>"); } // sudden death settings if (!settings.isDefaultSuddenDeath()) { out.println(" <sudden-death>"); if (!settings.isDefaultSuddenDeathTime()) { out.println(" <time>" + settings.getSuddenDeathTime() + "</time>"); } if (!settings.isDefaultSuddenDeathMessage()) { out.println(" <message>" + settings.getSuddenDeathMessage() + "</message>"); } if (!settings.isDefaultSuddenDeathDelay()) { out.println(" <delay>" + settings.getSuddenDeathDelay() + "</delay>"); } if (!settings.isDefaultSuddenDeathLinesAdded()) { out.println(" <lines-added>" + settings.getSuddenDeathLinesAdded() + "</lines-added>"); } out.println(" </sudden-death>"); } out.println(" </settings>"); } // local filters Collection<MessageFilter> filters = channel.getLocalFilters(); if (!filters.isEmpty()) { out.println(" <filters>"); for (MessageFilter filter : filters) { saveFilter(filter.getConfig(), out, " "); } out.println(" </filters>"); } out.println(" </channel>"); out.println(); } } out.println(" </channels>"); out.println(); out.println("</tetrinet-channels>"); out.close(); }
From source file:conf.Configuration.java
/** * Write out the non-default properties in this configuration to the given * {@link Writer}.//from w ww . j a v a 2s . co m * * @param out the writer to write to. */ public synchronized void writeXml(Writer out) throws IOException { Properties properties = getProps(); try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element conf = doc.createElement("configuration"); doc.appendChild(conf); conf.appendChild(doc.createTextNode("\n")); for (Enumeration e = properties.keys(); e.hasMoreElements();) { String name = (String) e.nextElement(); Object object = properties.get(name); String value = null; if (object instanceof String) { value = (String) object; } else { continue; } Element propNode = doc.createElement("property"); conf.appendChild(propNode); if (updatingResource != null) { Comment commentNode = doc.createComment("Loaded from " + updatingResource.get(name)); propNode.appendChild(commentNode); } Element nameNode = doc.createElement("name"); nameNode.appendChild(doc.createTextNode(name)); propNode.appendChild(nameNode); Element valueNode = doc.createElement("value"); valueNode.appendChild(doc.createTextNode(value)); propNode.appendChild(valueNode); conf.appendChild(doc.createTextNode("\n")); } DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.transform(source, result); } catch (TransformerException te) { throw new IOException(te); } catch (ParserConfigurationException pe) { throw new IOException(pe); } }
From source file:org.opencastproject.capture.impl.CaptureAgentImpl.java
/** * {@inheritDoc}// w w w . java 2 s. c om * * @see org.opencastproject.capture.api.CaptureAgent#startCapture(MediaPackage, Properties) */ @Override public String startCapture(MediaPackage mediaPackage, Properties properties) { logger.debug("startCapture(mediaPackage, properties): {} {}", mediaPackage, properties); // Stop the confidence monitoring if its pipeline is playing. if (confidence) { logger.info("Confidence monitoring disabled for capturing."); ConfidenceMonitorImpl.getInstance().stopMonitoring(); } // Check to make sure we're not already capturing something if (currentRecID != null || !agentState.equals(AgentState.IDLE)) { logger.warn("Unable to start capture, a different capture is still in progress in {}.", pendingRecordings.get(currentRecID).getBaseDir().getAbsolutePath()); // Set the recording's state to error if (properties != null && properties.getProperty(CaptureParameters.RECORDING_ID) != null) { setRecordingState(properties.getProperty(CaptureParameters.RECORDING_ID), RecordingState.CAPTURE_ERROR); } else { setRecordingState("Unscheduled-" + agentName + "-" + System.currentTimeMillis(), RecordingState.CAPTURE_ERROR); } return null; } else { setAgentState(AgentState.CAPTURING); } // Generate a combined properties object for this capture Properties capProperties = configService.merge(properties, false); // Create the recording RecordingImpl newRec = createRecording(mediaPackage, capProperties); if (newRec == null) { if (capProperties != null && capProperties.contains(CaptureParameters.RECORDING_ID)) { resetOnFailure((String) capProperties.get(CaptureParameters.RECORDING_ID)); } else { resetOnFailure("Unscheduled-" + agentName + "-" + System.currentTimeMillis()); } return null; } String recordingID = newRec.getID(); try { captureFramework.start(newRec, this); } catch (UnableToStartCaptureException exception) { logger.error(exception.getMessage()); resetOnFailure(newRec.getID()); return null; } // Keep track of how long it has been since the capture started. startTime = System.currentTimeMillis(); // Great, capture is running. Set the agent state appropriately. setRecordingState(recordingID, RecordingState.CAPTURING); // If the recording does *not* have a scheduled endpoint then schedule one. if (newRec.getProperty(CaptureParameters.RECORDING_END) == null) { if (!scheduleStop(newRec.getID())) { // If the attempt to schedule an end to the recording fails then shut everything down. stopCapture(newRec.getID(), false); resetOnFailure(newRec.getID()); } } serializeRecording(recordingID); return recordingID; }
From source file:com.evolveum.midpoint.notifications.impl.api.transports.MailTransport.java
@Override public void send(Message mailMessage, String transportName, Task task, OperationResult parentResult) { OperationResult result = parentResult.createSubresult(DOT_CLASS + "send"); result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo()); result.addParam("mailMessage subject", mailMessage.getSubject()); SystemConfigurationType systemConfiguration = NotificationsUtil .getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy")); if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) { String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg);//from w ww . j a v a 2 s . c om result.recordWarning(msg); return; } MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail(); String redirectToFile = mailConfigurationType.getRedirectToFile(); if (redirectToFile != null) { try { TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage)); result.recordSuccess(); } catch (IOException e) { LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile); result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e); } return; } if (mailConfigurationType.getServer().isEmpty()) { String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg); result.recordWarning(msg); return; } long start = System.currentTimeMillis(); String from = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org"; for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) { OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer"); final String host = mailServerConfigurationType.getHost(); resultForServer.addContext("server", host); resultForServer.addContext("port", mailServerConfigurationType.getPort()); Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); if (mailServerConfigurationType.getPort() != null) { properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort())); } MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType .getTransportSecurity(); boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false; switch (mailTransportSecurityType) { case STARTTLS_ENABLED: starttlsEnable = true; break; case STARTTLS_REQUIRED: starttlsEnable = true; starttlsRequired = true; break; case SSL: sslEnabled = true; break; } properties.put("mail.smtp.ssl.enable", "" + sslEnabled); properties.put("mail.smtp.starttls.enable", "" + starttlsEnable); properties.put("mail.smtp.starttls.required", "" + starttlsRequired); if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) { properties.put("mail.debug", "true"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using mail properties: "); for (Object key : properties.keySet()) { if (key instanceof String && ((String) key).startsWith("mail.")) { LOGGER.debug(" - " + key + " = " + properties.get(key)); } } } task.recordState("Sending notification mail via " + host); Session session = Session.getInstance(properties); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(from)); for (String recipient : mailMessage.getTo()) { mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); } mimeMessage.setSubject(mailMessage.getSubject(), "utf-8"); String contentType = mailMessage.getContentType(); if (StringUtils.isEmpty(contentType)) { contentType = "text/plain; charset=UTF-8"; } mimeMessage.setContent(mailMessage.getBody(), contentType); javax.mail.Transport t = session.getTransport("smtp"); if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) { ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword(); String password = null; if (passwordProtected != null) { try { password = protector.decryptString(passwordProtected); } catch (EncryptionException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any."; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); continue; } } t.connect(mailServerConfigurationType.getUsername(), password); } else { t.connect(); } t.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + "."); resultForServer.recordSuccess(); result.recordSuccess(); long duration = System.currentTimeMillis() - start; task.recordState( "Notification mail sent successfully via " + host + ", in " + duration + " ms overall."); task.recordNotificationOperation(NAME, true, duration); return; } catch (MessagingException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any"; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); task.recordState("Error sending notification mail via " + host); } } LOGGER.warn( "No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent."); result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent."); task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start); }