List of usage examples for java.util Properties putAll
@Override public synchronized void putAll(Map<?, ?> t)
From source file:com.alfaariss.oa.OAContextListener.java
/** * Starts the engine before all servlets are initialized. * //from w ww . j a v a2 s .c o m * Searches for the properties needed for the configuration in: * <code>[Servlet context dir]/WEB-INF/[PROPERTIES_FILENAME]</code> * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent oServletContextEvent) { Properties pConfig = new Properties(); try { _logger.info("Starting Asimba"); Package pCurrent = OAContextListener.class.getPackage(); String sSpecVersion = pCurrent.getSpecificationVersion(); if (sSpecVersion != null) _logger.info("Specification-Version: " + sSpecVersion); String sImplVersion = pCurrent.getImplementationVersion(); if (sImplVersion != null) _logger.info("Implementation-Version: " + sImplVersion); ServletContext oServletContext = oServletContextEvent.getServletContext(); Enumeration enumContextAttribs = oServletContext.getInitParameterNames(); while (enumContextAttribs.hasMoreElements()) { String sName = (String) enumContextAttribs.nextElement(); pConfig.put(sName, oServletContext.getInitParameter(sName)); } if (pConfig.size() > 0) { _logger.info("Using configuration items found in servlet context: " + pConfig); } // Add MountingPoint to PathTranslator PathTranslator.getInstance().addKey(MP_WEBAPP_ROOT, oServletContext.getRealPath("")); // Try to see whether there is a system property with the location of the properties file: String sPropertiesFilename = System.getProperty(PROPERTIES_FILENAME_PROPERTY); if (null != sPropertiesFilename && !"".equals(sPropertiesFilename)) { File fConfig = new File(sPropertiesFilename); if (fConfig.exists()) { _logger.info("Reading Asimba properties from " + fConfig.getAbsolutePath()); pConfig.putAll(getProperties(fConfig)); } } String sWebInf = oServletContext.getRealPath("WEB-INF"); if (sWebInf != null) { _logger.info("Cannot find path in ServletContext for WEB-INF"); StringBuffer sbConfigFile = new StringBuffer(sWebInf); if (!sbConfigFile.toString().endsWith(File.separator)) sbConfigFile.append(File.separator); sbConfigFile.append(PROPERTIES_FILENAME); File fConfig = new File(sbConfigFile.toString()); if (fConfig.exists()) { _logger.info("Updating configuration items with the items in file: " + fConfig.toString()); pConfig.putAll(getProperties(fConfig)); } else { _logger.info("No optional configuration properties (" + PROPERTIES_FILENAME + ") file found at: " + fConfig.toString()); } } //Search for PROPERTIES_FILENAME file in servlet context classloader classpath //it looks first at this location: ./<context>/web-inf/classes/[PROPERTIES_FILENAME] //if previous location didn't contain PROPERTIES_FILENAME then checking: //./tomcat/common/classes/PROPERTIES_FILENAME URL urlProperties = oServletContext.getClass().getClassLoader().getResource(PROPERTIES_FILENAME); if (urlProperties != null) { String sProperties = urlProperties.getFile(); _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in classpath: " + sProperties); File fProperties = new File(sProperties); if (fProperties != null && fProperties.exists()) { _logger.info("Updating configuration items with the items in file: " + fProperties.getAbsolutePath()); pConfig.putAll(getProperties(fProperties)); } else _logger.info("Could not resolve: " + fProperties.getAbsolutePath()); } else _logger.info("No optional '" + PROPERTIES_FILENAME + "' configuration file found in servlet context classpath"); if (!pConfig.containsKey("configuration.handler.filename")) { StringBuffer sbOAConfigFile = new StringBuffer(sWebInf); if (!sbOAConfigFile.toString().endsWith(File.separator)) sbOAConfigFile.append(File.separator); sbOAConfigFile.append("conf"); sbOAConfigFile.append(File.separator); sbOAConfigFile.append("asimba.xml"); File fOAConfig = new File(sbOAConfigFile.toString()); if (fOAConfig.exists()) { pConfig.put("configuration.handler.filename", sbOAConfigFile.toString()); _logger.info( "Setting 'configuration.handler.filename' configuration property with configuration file found at: " + fOAConfig.toString()); } } _oEngineLauncher.start(pConfig); _logger.info("Started Engine with OAContextListener"); } catch (Exception e) { _logger.error("Can't start Engine with OAContextListener", e); _logger.debug("try stopping the server"); _oEngineLauncher.stop(); } }
From source file:org.schemaspy.Config.java
/** * Determines the database properties associated with the specified type. * A call to {@link #setDbProperties(Properties)} is expected after determining * the complete set of properties.//from www . ja v a 2 s . c om * * @param type * @return * @throws IOException * @throws InvalidConfigurationException if db properties are incorrectly formed */ public Properties determineDbProperties(String type) throws IOException, InvalidConfigurationException { ResourceBundle bundle = null; try { File propertiesFile = new File(type); bundle = new PropertyResourceBundle(new FileInputStream(propertiesFile)); dbPropertiesLoadedFrom = propertiesFile.getAbsolutePath(); } catch (FileNotFoundException notFoundOnFilesystemWithoutExtension) { try { File propertiesFile = new File(type + ".properties"); bundle = new PropertyResourceBundle(new FileInputStream(propertiesFile)); dbPropertiesLoadedFrom = propertiesFile.getAbsolutePath(); } catch (FileNotFoundException notFoundOnFilesystemWithExtensionTackedOn) { try { bundle = ResourceBundle.getBundle(type); dbPropertiesLoadedFrom = "[" + getLoadedFromJar() + "]" + File.separator + type + ".properties"; } catch (Exception notInJarWithoutPath) { try { String path = TableOrderer.class.getPackage().getName() + ".types." + type; path = path.replace('.', '/'); bundle = ResourceBundle.getBundle(path); dbPropertiesLoadedFrom = "[" + getLoadedFromJar() + "]/" + path + ".properties"; } catch (Exception notInJar) { notInJar.printStackTrace(); notFoundOnFilesystemWithExtensionTackedOn.printStackTrace(); throw notFoundOnFilesystemWithoutExtension; } } } } Properties props = asProperties(bundle); bundle = null; String saveLoadedFrom = dbPropertiesLoadedFrom; // keep original thru recursion // bring in key/values pointed to by the include directive // example: include.1=mysql::selectRowCountSql for (int i = 1; true; ++i) { String include = (String) props.remove("include." + i); if (include == null) break; int separator = include.indexOf("::"); if (separator == -1) throw new InvalidConfigurationException("include directive in " + dbPropertiesLoadedFrom + " must have '::' between dbType and key"); String refdType = include.substring(0, separator).trim(); String refdKey = include.substring(separator + 2).trim(); // recursively resolve the ref'd properties file and the ref'd key Properties refdProps = determineDbProperties(refdType); props.put(refdKey, refdProps.getProperty(refdKey)); } // bring in base properties files pointed to by the extends directive String baseDbType = (String) props.remove("extends"); if (baseDbType != null) { baseDbType = baseDbType.trim(); Properties baseProps = determineDbProperties(baseDbType); // overlay our properties on top of the base's baseProps.putAll(props); props = baseProps; } // done with this level of recursion...restore original dbPropertiesLoadedFrom = saveLoadedFrom; // this won't be correct until the final recursion exits dbProperties = props; return props; }
From source file:org.apache.tajo.jdbc.JdbcConnection.java
public JdbcConnection(String rawURI, Properties properties) throws SQLException { this.rawURI = rawURI; this.properties = properties; try {/*from w w w . jav a 2s .c o m*/ if (!rawURI.startsWith(TajoDriver.TAJO_JDBC_URL_PREFIX)) { // its impossible case throw new TajoInternalError("Invalid URL: " + rawURI); } // URI form: jdbc:tajo://hostname:port/databasename int startIdx = rawURI.indexOf(":"); if (startIdx < 0) { throw new TajoInternalError("Invalid URL: " + rawURI); } String uri = rawURI.substring(startIdx + 1, rawURI.length()); try { this.uri = URI.create(uri); } catch (IllegalArgumentException iae) { throw new SQLException("Invalid URL: " + rawURI, "TAJO-001"); } hostName = this.uri.getHost(); if (hostName == null) { throw new SQLException("Invalid JDBC URI: " + rawURI, "TAJO-001"); } if (this.uri.getPort() < 1) { port = 26002; } else { port = this.uri.getPort(); } if (this.uri.getPath() == null || this.uri.getPath().equalsIgnoreCase("")) { // if no database is given, set default. databaseName = TajoConstants.DEFAULT_DATABASE_NAME; } else { // getPath() will return '/database'. databaseName = this.uri.getPath().split("/")[1]; } params = new QueryStringDecoder(rawURI).getParameters(); properties.putAll(params); } catch (SQLException se) { throw se; } catch (Throwable t) { // for unexpected exceptions like ArrayIndexOutOfBoundsException. throw new SQLException("Invalid JDBC URI: " + rawURI, "TAJO-001"); } clientProperties = new KeyValueSet(); if (properties != null) { for (Map.Entry<Object, Object> entry : properties.entrySet()) { if (entry.getValue() instanceof Collection) { clientProperties.set(entry.getKey().toString(), StringUtils.join((Collection) entry.getValue(), ",")); } else { clientProperties.set(entry.getKey().toString(), entry.getValue().toString()); } } } try { tajoClient = new TajoClientImpl(RpcUtils.createSocketAddr(hostName, port), databaseName, clientProperties); } catch (Throwable t) { if (t instanceof DefaultTajoException) { throw SQLExceptionUtil.toSQLException((DefaultTajoException) t); } else { throw new TajoSQLException(ResultCode.INTERNAL_ERROR, t, t.getMessage()); } } closed.set(false); }
From source file:de.uni_hildesheim.sse.easy_producer.instantiator.model.buildlangModel.BuildlangExecution.java
/** * Loads properties from <code>file</code> into <code>prop</code> possibly overriding existing * properties. /*from w w w .java 2s . com*/ * * @param file the file name * @param prop the loaded properties (to be modified as a side effect) * @param os if not <b>null</b> to be inserted after the last "." with a following ".". If file * not exists, no exception will be thrown. * @throws VilLanguageException in case of loading problems */ private void loadProperties(File file, Properties prop, String os) throws VilLanguageException { boolean loadFile = true; if (null != os) { String f = file.toString(); int pos = f.lastIndexOf('.'); if (pos > 0 && pos < f.length()) { f = f.substring(0, pos + 1) + os + "." + f.substring(pos + 1); file = new File(f); loadFile = file.exists(); } else { loadFile = false; } } if (loadFile) { try { FileInputStream fis = new FileInputStream(file); Properties p = new Properties(); p.load(fis); prop.putAll(p); fis.close(); } catch (IOException e) { throw new VilLanguageException(e.getMessage(), e, VilLanguageException.ID_IO); } } }
From source file:org.apache.maven.plugin.invoker.AbstractInvokerMojo.java
/** * Gets the system properties to use for the specified project. * * @param basedir The base directory of the project, must not be <code>null</code>. * @param filename The filename to the properties file to load, may be <code>null</code> to use the default path * given by {@link #testPropertiesFile}. * @return The system properties to use, may be empty but never <code>null</code>. * @throws org.apache.maven.plugin.MojoExecutionException * If the properties file exists but could not be read. *//*from ww w . j a v a2 s. c o m*/ private Properties getSystemProperties(final File basedir, final String filename) throws MojoExecutionException { Properties collectedTestProperties = new Properties(); if (testProperties != null) { collectedTestProperties.putAll(testProperties); } if (properties != null) { // MINVOKER-118: property can have empty value, which is not accepted by collectedTestProperties for (Map.Entry<String, String> entry : properties.entrySet()) { if (entry.getValue() != null) { collectedTestProperties.put(entry.getKey(), entry.getValue()); } } } File propertiesFile = null; if (filename != null) { propertiesFile = new File(basedir, filename); } else if (testPropertiesFile != null) { propertiesFile = new File(basedir, testPropertiesFile); } if (propertiesFile != null && propertiesFile.isFile()) { InputStream fin = null; try { fin = new FileInputStream(propertiesFile); Properties loadedProperties = new Properties(); loadedProperties.load(fin); collectedTestProperties.putAll(loadedProperties); } catch (IOException e) { throw new MojoExecutionException("Error reading system properties from " + propertiesFile); } finally { IOUtil.close(fin); } } return collectedTestProperties; }
From source file:org.apache.jmeter.JMeter.java
private void initializeProperties(CLArgsParser parser) { if (parser.getArgumentById(PROPFILE_OPT) != null) { JMeterUtils.loadJMeterProperties(parser.getArgumentById(PROPFILE_OPT).getArgument()); } else {//from ww w .j a v a 2 s .c om JMeterUtils.loadJMeterProperties(NewDriver.getJMeterDir() + File.separator + "bin" + File.separator // $NON-NLS-1$ + "jmeter.properties");// $NON-NLS-1$ } if (parser.getArgumentById(JMLOGFILE_OPT) != null) { String jmlogfile = parser.getArgumentById(JMLOGFILE_OPT).getArgument(); jmlogfile = processLAST(jmlogfile, ".log");// $NON-NLS-1$ JMeterUtils.setProperty(LoggingManager.LOG_FILE, jmlogfile); } JMeterUtils.initLogging(); JMeterUtils.initLocale(); // Bug 33845 - allow direct override of Home dir if (parser.getArgumentById(JMETER_HOME_OPT) == null) { JMeterUtils.setJMeterHome(NewDriver.getJMeterDir()); } else { JMeterUtils.setJMeterHome(parser.getArgumentById(JMETER_HOME_OPT).getArgument()); } Properties jmeterProps = JMeterUtils.getJMeterProperties(); remoteProps = new Properties(); // Add local JMeter properties, if the file is found String userProp = JMeterUtils.getPropDefault("user.properties", ""); //$NON-NLS-1$ if (userProp.length() > 0) { //$NON-NLS-1$ FileInputStream fis = null; try { File file = JMeterUtils.findFile(userProp); if (file.canRead()) { log.info("Loading user properties from: " + file.getCanonicalPath()); fis = new FileInputStream(file); Properties tmp = new Properties(); tmp.load(fis); jmeterProps.putAll(tmp); LoggingManager.setLoggingLevels(tmp);//Do what would be done earlier } } catch (IOException e) { log.warn("Error loading user property file: " + userProp, e); } finally { JOrphanUtils.closeQuietly(fis); } } // Add local system properties, if the file is found String sysProp = JMeterUtils.getPropDefault("system.properties", ""); //$NON-NLS-1$ if (sysProp.length() > 0) { FileInputStream fis = null; try { File file = JMeterUtils.findFile(sysProp); if (file.canRead()) { log.info("Loading system properties from: " + file.getCanonicalPath()); fis = new FileInputStream(file); System.getProperties().load(fis); } } catch (IOException e) { log.warn("Error loading system property file: " + sysProp, e); } finally { JOrphanUtils.closeQuietly(fis); } } // Process command line property definitions // These can potentially occur multiple times List<CLOption> clOptions = parser.getArguments(); for (CLOption option : clOptions) { String name = option.getArgument(0); String value = option.getArgument(1); FileInputStream fis = null; switch (option.getDescriptor().getId()) { // Should not have any text arguments case CLOption.TEXT_ARGUMENT: throw new IllegalArgumentException("Unknown arg: " + option.getArgument()); case PROPFILE2_OPT: // Bug 33920 - allow multiple props try { fis = new FileInputStream(new File(name)); Properties tmp = new Properties(); tmp.load(fis); jmeterProps.putAll(tmp); LoggingManager.setLoggingLevels(tmp);//Do what would be done earlier } catch (FileNotFoundException e) { log.warn("Can't find additional property file: " + name, e); } catch (IOException e) { log.warn("Error loading additional property file: " + name, e); } finally { JOrphanUtils.closeQuietly(fis); } break; case SYSTEM_PROPFILE: log.info("Setting System properties from file: " + name); try { fis = new FileInputStream(new File(name)); System.getProperties().load(fis); } catch (IOException e) { log.warn("Cannot find system property file " + e.getLocalizedMessage()); } finally { JOrphanUtils.closeQuietly(fis); } break; case SYSTEM_PROPERTY: if (value.length() > 0) { // Set it log.info("Setting System property: " + name + "=" + value); System.getProperties().setProperty(name, value); } else { // Reset it log.warn("Removing System property: " + name); System.getProperties().remove(name); } break; case JMETER_PROPERTY: if (value.length() > 0) { // Set it log.info("Setting JMeter property: " + name + "=" + value); jmeterProps.setProperty(name, value); } else { // Reset it log.warn("Removing JMeter property: " + name); jmeterProps.remove(name); } break; case JMETER_GLOBAL_PROP: if (value.length() > 0) { // Set it log.info("Setting Global property: " + name + "=" + value); remoteProps.setProperty(name, value); } else { File propFile = new File(name); if (propFile.canRead()) { log.info("Setting Global properties from the file " + name); try { fis = new FileInputStream(propFile); remoteProps.load(fis); } catch (FileNotFoundException e) { log.warn("Could not find properties file: " + e.getLocalizedMessage()); } catch (IOException e) { log.warn("Could not load properties file: " + e.getLocalizedMessage()); } finally { JOrphanUtils.closeQuietly(fis); } } } break; case LOGLEVEL: if (value.length() > 0) { // Set category log.info("LogLevel: " + name + "=" + value); LoggingManager.setPriority(value, name); } else { // Set root level log.warn("LogLevel: " + name); LoggingManager.setPriority(name); } break; case REMOTE_STOP: remoteStop = true; break; default: // ignored break; } } String sampleVariables = (String) jmeterProps.get(SampleEvent.SAMPLE_VARIABLES); if (sampleVariables != null) { remoteProps.put(SampleEvent.SAMPLE_VARIABLES, sampleVariables); } jmeterProps.put("jmeter.version", JMeterUtils.getJMeterVersion()); }
From source file:org.apache.falcon.oozie.feed.FeedReplicationCoordinatorBuilder.java
private ACTION getReplicationWorkflowAction(Cluster srcCluster, Cluster trgCluster, Path buildPath, String wfName, Storage sourceStorage, Storage targetStorage) throws FalconException { ACTION action = new ACTION(); WORKFLOW workflow = new WORKFLOW(); workflow.setAppPath(getStoragePath(buildPath)); Properties props = createCoordDefaultConfiguration(wfName); // Override CLUSTER_NAME property to include both source and target cluster pair String clusterProperty = trgCluster.getName() + WorkflowExecutionContext.CLUSTER_NAME_SEPARATOR + srcCluster.getName();//from w ww.j a v a 2s. co m props.put(WorkflowExecutionArgs.CLUSTER_NAME.getName(), clusterProperty); props.put("srcClusterName", srcCluster.getName()); props.put("srcClusterColo", srcCluster.getColo()); // the storage type is uniform across source and target feeds for replication props.put("falconFeedStorageType", sourceStorage.getType().name()); String instancePaths = ""; if (sourceStorage.getType() == Storage.TYPE.FILESYSTEM) { String pathsWithPartitions = getPathsWithPartitions(srcCluster, trgCluster); instancePaths = pathsWithPartitions; propagateFileSystemCopyProperties(pathsWithPartitions, props); } else if (sourceStorage.getType() == Storage.TYPE.TABLE) { instancePaths = "${coord:dataIn('input')}"; final CatalogStorage sourceTableStorage = (CatalogStorage) sourceStorage; propagateTableStorageProperties(srcCluster, sourceTableStorage, props, "falconSource"); final CatalogStorage targetTableStorage = (CatalogStorage) targetStorage; propagateTableStorageProperties(trgCluster, targetTableStorage, props, "falconTarget"); propagateTableCopyProperties(srcCluster, sourceTableStorage, trgCluster, targetTableStorage, props); setupHiveConfiguration(srcCluster, trgCluster, buildPath); } propagateLateDataProperties(instancePaths, sourceStorage.getType().name(), props); // Add the custom properties set in feed. Else, dryrun won't catch any missing props. props.putAll(getEntityProperties(entity)); workflow.setConfiguration(getConfig(props)); action.setWorkflow(workflow); return action; }
From source file:org.apache.druid.indexing.kafka.supervisor.KafkaSupervisor.java
private KafkaConsumer<byte[], byte[]> getKafkaConsumer() { final Properties props = new Properties(); props.setProperty("metadata.max.age.ms", "10000"); props.setProperty("group.id", StringUtils.format("kafka-supervisor-%s", RealtimeIndexTask.makeRandomId())); props.putAll(ioConfig.getConsumerProperties()); props.setProperty("enable.auto.commit", "false"); ClassLoader currCtxCl = Thread.currentThread().getContextClassLoader(); try {//from w w w. j av a 2s . c o m Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); return new KafkaConsumer<>(props, new ByteArrayDeserializer(), new ByteArrayDeserializer()); } finally { Thread.currentThread().setContextClassLoader(currCtxCl); } }
From source file:org.apache.flink.streaming.connectors.kafka.KafkaConsumerTestBase.java
/** * Test that ensures that DeserializationSchema.isEndOfStream() is properly evaluated. * * @throws Exception//from ww w . j a v a 2s .c o m */ public void runEndOfStreamTest() throws Exception { final int ELEMENT_COUNT = 300; final String topic = writeSequence("testEndOfStream", ELEMENT_COUNT, 1, 1); // read using custom schema final StreamExecutionEnvironment env1 = StreamExecutionEnvironment.createRemoteEnvironment("localhost", flinkPort); env1.setParallelism(1); env1.getConfig().setRestartStrategy(RestartStrategies.noRestart()); env1.getConfig().disableSysoutLogging(); Properties props = new Properties(); props.putAll(standardProps); props.putAll(secureProps); DataStream<Tuple2<Integer, Integer>> fromKafka = env1.addSource( kafkaServer.getConsumer(topic, new FixedNumberDeserializationSchema(ELEMENT_COUNT), props)); fromKafka.flatMap(new FlatMapFunction<Tuple2<Integer, Integer>, Void>() { @Override public void flatMap(Tuple2<Integer, Integer> value, Collector<Void> out) throws Exception { // noop ;) } }); JobExecutionResult result = tryExecute(env1, "Consume " + ELEMENT_COUNT + " elements from Kafka"); deleteTestTopic(topic); }