Java Code Examples for java.util.Properties#putAll()

The following examples show how to use java.util.Properties#putAll() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SingletonContext.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Initialize singleton context using custom properties
 * 
 * This method can only be called once.
 * 
 * @param props
 * @throws CIFSException
 */
public static synchronized final void init ( Properties props ) throws CIFSException {
    if ( INSTANCE != null ) {
        throw new CIFSException("Singleton context is already initialized");
    }
    Properties p = new Properties();
    try {
        String filename = System.getProperty("jcifs.properties");
        if ( filename != null && filename.length() > 1 ) {

            try ( FileInputStream in = new FileInputStream(filename) ) {
                p.load(in);
            }
        }

    }
    catch ( IOException ioe ) {
        log.error("Failed to load config", ioe); //$NON-NLS-1$
    }
    p.putAll(System.getProperties());
    if ( props != null ) {
        p.putAll(props);
    }
    INSTANCE = new SingletonContext(p);
}
 
Example 2
Source File: Placement.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Properties getConfig()
{
	// the placement config overrides registered config
	Properties p = new Properties();

	// put the mutable registered ones in, and do it first so that the placement can override
	if (m_tool != null)
	{
		p.putAll(m_tool.getMutableConfig());
	}

	// put the placement properties in
	p.putAll(getPlacementConfig());

	// put the final registered ones in last so they cannot be overriden by the placement
	if (m_tool != null)
	{
		p.putAll(m_tool.getFinalConfig());
	}
	
	return p;
}
 
Example 3
Source File: KafkaConsumerProperties.java    From kylin with Apache License 2.0 5 votes vote down vote up
private Properties loadKafkaConsumerProperties() {
    File propFile = getKafkaConsumerFile();
    if (propFile == null || !propFile.exists()) {
        logger.warn("fail to locate {}, use empty kafka consumer properties", KAFKA_CONSUMER_FILE);
        return new Properties();
    }
    Properties properties = new Properties();
    try (FileInputStream is = new FileInputStream(propFile)) {
        Configuration conf = new Configuration();
        conf.addResource(is);
        properties.putAll(extractKafkaConfigToProperties(conf));

        File propOverrideFile = new File(propFile.getParentFile(), propFile.getName() + ".override");
        if (propOverrideFile.exists()) {
            try (FileInputStream ois = new FileInputStream(propOverrideFile)) {
                Configuration oconf = new Configuration();
                oconf.addResource(ois);
                properties.putAll(extractKafkaConfigToProperties(oconf));
            }
        }
    } catch (FileNotFoundException fne) {
        throw new IllegalArgumentException(fne);
    } catch (IOException e) {
        // close inputStream quietly
    }

    return properties;
}
 
Example 4
Source File: ConfigPropertiesFactoryBean.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
protected void loadProperties(Properties props) throws IOException {
    super.loadProperties(props);
    Map riceProperties;
    if (prefix != null) {
        riceProperties = ConfigContext.getCurrentContextConfig().getPropertiesWithPrefix(prefix, true);
    } else {
        riceProperties = ConfigContext.getCurrentContextConfig().getProperties();
    }
    props.putAll(riceProperties);
}
 
Example 5
Source File: PropertiesReplacementUtil.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
/**
    * Loads the given file into a Properties object.
    * @param base Properties that should override those loaded from the file
    * @param file The file to load
    * @return Properties loaded from the file
    */
   static public Properties loadProperties(Properties base, File file) throws IOException {
FileReader reader = new FileReader(file);
Properties props = new Properties();
props.load(reader);
if (base != null) props.putAll(base);
reader.close();
return props;
   }
 
Example 6
Source File: KafkaConsumerTestBase.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Test that ensures the KafkaConsumer is properly failing if the topic doesnt exist
 * and a wrong broker was specified.
 *
 * @throws Exception
 */
public void runFailOnNoBrokerTest() throws Exception {
	try {
		Properties properties = new Properties();

		StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment();
		see.getConfig().disableSysoutLogging();
		see.setRestartStrategy(RestartStrategies.noRestart());
		see.setParallelism(1);

		// use wrong ports for the consumers
		properties.setProperty("bootstrap.servers", "localhost:80");
		properties.setProperty("group.id", "test");
		properties.setProperty("request.timeout.ms", "3000"); // let the test fail fast
		properties.setProperty("socket.timeout.ms", "3000");
		properties.setProperty("session.timeout.ms", "2000");
		properties.setProperty("fetch.max.wait.ms", "2000");
		properties.setProperty("heartbeat.interval.ms", "1000");
		properties.putAll(secureProps);
		FlinkKafkaConsumerBase<String> source = kafkaServer.getConsumer("doesntexist", new SimpleStringSchema(), properties);
		DataStream<String> stream = see.addSource(source);
		stream.print();
		see.execute("No broker test");
	} catch (JobExecutionException jee) {
		if (kafkaServer.getVersion().equals("0.9") ||
			kafkaServer.getVersion().equals("0.10") ||
			kafkaServer.getVersion().equals("0.11") ||
			kafkaServer.getVersion().equals("2.0")) {
			final Optional<TimeoutException> optionalTimeoutException = ExceptionUtils.findThrowable(jee, TimeoutException.class);
			assertTrue(optionalTimeoutException.isPresent());

			final TimeoutException timeoutException = optionalTimeoutException.get();
			assertEquals("Timeout expired while fetching topic metadata", timeoutException.getMessage());
		} else {
			final Optional<Throwable> optionalThrowable = ExceptionUtils.findThrowableWithMessage(jee, "Unable to retrieve any partitions");
			assertTrue(optionalThrowable.isPresent());
			assertTrue(optionalThrowable.get() instanceof RuntimeException);
		}
	}
}
 
Example 7
Source File: KafkaTestEnvironmentImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public KafkaOffsetHandlerImpl() {
	Properties props = new Properties();
	props.putAll(standardProps);
	props.setProperty("key.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
	props.setProperty("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");

	offsetClient = new KafkaConsumer<>(props);
}
 
Example 8
Source File: ReplicationMySQLConnection.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Properties getProperties() {
    Properties props = new Properties();
    JdbcConnection conn;
    if ((conn = getValidatedMasterConnection()) != null) {
        props.putAll(conn.getProperties());
    }
    if ((conn = getValidatedSlavesConnection()) != null) {
        props.putAll(conn.getProperties());
    }

    return props;
}
 
Example 9
Source File: MapTypeHandler.java    From mybatis-types with MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Map<String, String> parameter, JdbcType jdbcType) throws SQLException {
    Properties properties = new Properties();
    properties.putAll(parameter);
    StringWriter sw = new StringWriter();
    try {
        properties.store(sw, "Generated by mybatis-types");
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
    ps.setString(i, sw.toString());
}
 
Example 10
Source File: TGResourceBundle.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void loadResources(TGContext context, String name, Properties p){
	try {
		Enumeration<URL> enumeration = TGResourceManager.getInstance(context).getResources(name);
		while (enumeration.hasMoreElements()) {
			URL url = (URL) enumeration.nextElement();
			Properties properties = new Properties();
			properties.load( url.openStream() );
			p.putAll(properties);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 11
Source File: ConnectionUrl.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a {@link Properties} instance containing the connection arguments extracted from the URL query section, i.e., per host attributes are excluded.
 * Applies properties transformations to the collected properties if {@link ConnectionPropertiesTransform} was declared in the connection arguments.
 *
 * @return a {@link Properties} instance containing the common connection arguments.
 */
public Properties getConnectionArgumentsAsProperties() {
    Properties props = new Properties();
    if (this.properties != null) {
        props.putAll(this.properties);
    }

    return this.propertiesTransformer != null ? this.propertiesTransformer.transformProperties(props) : props;
}
 
Example 12
Source File: FlinkKafkaProducerMigrationTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
protected Properties createProperties() {
	Properties properties = new Properties();
	properties.putAll(standardProps);
	properties.putAll(secureProps);
	properties.put(ProducerConfig.CLIENT_ID_CONFIG, "producer-client-id");
	properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "producer-transaction-id");
	properties.put(FlinkKafkaProducer.KEY_DISABLE_METRICS, "true");
	return properties;
}
 
Example 13
Source File: SolrConfig.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public Properties getSubstituteProperties() {
  Map<String, Object> p = getOverlay().getUserProps();
  if (p == null || p.isEmpty()) return super.getSubstituteProperties();
  Properties result = new Properties(super.getSubstituteProperties());
  result.putAll(p);
  return result;
}
 
Example 14
Source File: SqlManager.java    From ReplicaDB with Apache License 2.0 4 votes vote down vote up
/**
 * Create a connection to the database; usually used only from within
 * getConnection(), which enforces a singleton guarantee around the
 * Connection object.
 */
protected Connection makeSourceConnection() throws SQLException {

    Connection connection;
    String driverClass = getDriverClass();

    try {
        Class.forName(driverClass);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException("Could not load db driver class: "
                + driverClass);
    }

    String username = options.getSourceUser();
    String password = options.getSourcePassword();
    String connectString = options.getSourceConnect();

    Properties connectionParams = options.getSourceConnectionParams();
    if (connectionParams != null && connectionParams.size() > 0) {
        LOG.debug("User specified connection params. Using properties specific API for making connection.");

        Properties props = new Properties();
        if (username != null) {
            props.put("user", username);
        }

        if (password != null) {
            props.put("password", password);
        }

        props.putAll(connectionParams);
        connection = DriverManager.getConnection(connectString, props);
    } else {
        LOG.debug("No connection parameters specified. Using regular API for making connection.");
        if (username == null) {
            connection = DriverManager.getConnection(connectString);
        } else {
            connection = DriverManager.getConnection(connectString, username, password);
        }
    }

    // We only use this for metadata queries. Loosest semantics are okay.
    //connection.setTransactionIsolation(getMetadataIsolationLevel());
    connection.setAutoCommit(false);

    return connection;
}
 
Example 15
Source File: DoxiaSiteRenderer.java    From helidon-build-tools with Apache License 2.0 4 votes vote down vote up
@Override
public void render(Collection<DocumentRenderer> documents, SiteRenderingContext context, File outputDirectory)
        throws RendererException, IOException {

    for (DocumentRenderer docRenderer : documents) {
        if (!(docRenderer instanceof ReportDocumentRenderer)) {
            continue;
        }
        RenderingContext renderingContext = docRenderer.getRenderingContext();
        File outputFile = new File(outputDirectory, docRenderer.getOutputName());
        File inputFile = new File(renderingContext.getBasedir(), renderingContext.getInputName());
        boolean modified = !outputFile.exists()
                || (inputFile.lastModified() > outputFile.lastModified())
                || (context.getDecoration().getLastModified() > outputFile.lastModified());

        if (modified || docRenderer.isOverwrite()) {
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }

            if (getLogger().isDebugEnabled()) {
                getLogger().debug("Generating " + outputFile);
            }

            Writer writer = null;
            try {
                if (!docRenderer.isExternalReport()) {
                    writer = WriterFactory.newWriter(outputFile, context.getOutputEncoding());
                }
                docRenderer.renderDocument(writer, this, context);
            } finally {
                IOUtil.close(writer);
            }
        } else {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug(inputFile + " unchanged, not regenerating...");
            }
        }
    }

    Properties properties = new Properties();
    Map<String, ?> templateProps = context.getTemplateProperties();
    if (templateProps != null) {
        properties.putAll(templateProps);
        MavenProject project = (MavenProject) templateProps.get("project");
        if (project != null) {
            properties.setProperty("project.groupId", project.getGroupId());
            properties.setProperty("project.artifactId", project.getArtifactId());
            properties.setProperty("project.version", project.getVersion());
            properties.setProperty("project.basedir", project.getBasedir().getAbsolutePath());
        }
    }

    File siteDirectory = context.getSiteDirectories().iterator().next();
    File siteConfigFile = new File(siteDirectory, "sitegen.yaml");
    Site site = Site.builder()
            .config(siteConfigFile, properties)
            .build();

    // enable jruby verbose mode on debugging
    if (getLogger().isDebugEnabled()) {
        System.setProperty("jruby.cli.verbose", "true");
    }

    try {
        site.generate(siteDirectory, outputDirectory);
    } catch (RenderingException ex) {
        throw new RendererException(ex.getMessage(), ex);
    }
}
 
Example 16
Source File: Environment.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Return <tt>System</tt> properties, extended by any properties specified
 * in <tt>hibernate.properties</tt>.
 * @return Properties
 */
public static Properties getProperties() {
	Properties copy = new Properties();
	copy.putAll(GLOBAL_PROPERTIES);
	return copy;
}
 
Example 17
Source File: HierarchicalAnomaliesContent.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
/**
 * Generate the AnomalyReportEntity
 * @param anomaly
 * @param dashboardHost
 * @return
 */
private AnomalyReportEntity generateAnomalyReportEntity(MergedAnomalyResultDTO anomaly, String dashboardHost) {
  AnomalyFeedback feedback = anomaly.getFeedback();

  String feedbackVal = getFeedbackValue(feedback);

  Properties props = new Properties();
  props.putAll(anomaly.getProperties());
  double lift = BaseNotificationContent.getLift(anomaly.getAvgCurrentVal(), anomaly.getAvgBaselineVal());
  AnomalyReportEntity
      anomalyReport = new AnomalyReportEntity(String.valueOf(anomaly.getId()),
      getAnomalyURL(anomaly, dashboardHost),
      getPredictedValue(anomaly),
      getCurrentValue(anomaly),
      getFormattedLiftValue(anomaly, lift),
      getLiftDirection(lift),
      anomaly.getImpactToGlobal(),
      getDimensionsList(anomaly.getDimensionMap()),
      getTimeDiffInHours(anomaly.getStartTime(), anomaly.getEndTime()), // duration
      feedbackVal,
      anomaly.getFunction().getFunctionName(),
      "",
      anomaly.getMetric(),
      getDateString(anomaly.getStartTime(), dateTimeZone),
      getDateString(anomaly.getEndTime(), dateTimeZone),
      getTimezoneString(dateTimeZone),
      getIssueType(anomaly),
      anomaly.getType().getLabel(),
      ThirdEyeStringUtils.encodeCompactedProperties(props)

  );

  List<String> affectedCountries = getMatchedFilterValues(anomaly, "country");
  if (affectedCountries.size() > 0) { // if the anomaly is on country level
    Map<String, List<String>> targetDimensions = new HashMap<>();
    targetDimensions.put(EVENT_FILTER_COUNTRY, affectedCountries);
    relatedEvents.addAll(getHolidayEvents(
        new DateTime(anomaly.getStartTime(), dateTimeZone),
        new DateTime(anomaly.getEndTime(), dateTimeZone),
        targetDimensions));
  }

  return anomalyReport;
}
 
Example 18
Source File: Config.java    From wings with Apache License 2.0 4 votes vote down vote up
public Properties getProperties(Domain domain) {
    Properties props = new Properties();
    if (domain != null) {
        props = domain.getProperties();
        if (domain.isLegacy())
            return props;

        props.setProperty("ont.dir.url", this.ontdirurl);
        if (!domain.getUseSharedTripleStore())
            props.setProperty("ont.dir.map",
                    "file:" + domain.getDomainDirectory() + File.separator + "ontology");

        props.setProperty("ont.data.url", this.getDataOntologyUrl());
        props.setProperty("ont.component.url", this.getComponentOntologyUrl());
        props.setProperty("ont.workflow.url", this.getWorkflowOntologyUrl());
        props.setProperty("ont.execution.url", this.getExecutionOntologyUrl());
        if (domain.getUseSharedTripleStore())
            props.setProperty("tdb.repository.dir", this.getTripleStoreDir());

        ExeEngine pengine = engines.get(domain.getPlanEngine());
        ExeEngine sengine = engines.get(domain.getStepEngine());
        props.putAll(pengine.getProperties());
        props.putAll(sengine.getProperties());
    } else {
        props.setProperty("tdb.repository.dir", this.getTripleStoreDir());
    }
    props.setProperty("logs.dir", this.getLogsDirectory());
    props.setProperty("dot.path", this.getDotFile());

    if (this.getResourceOntologyUrl() == null)
        this.setResourceOntologyUrl(ontdirurl + "/resource.owl");
    props.setProperty("ont.resource.url", this.getResourceOntologyUrl());
    
    props.setProperty("lib.resource.url",
            this.getExportCommunityUrl() + "/resource/library.owl");

    if (domain != null && !domain.getUseSharedTripleStore())
      props.setProperty("lib.resource.map",
          "file:" + domain.getDomainDirectory() + File.separator + "ontology" 
              + File.separator + "resource" + File.separator + "library.owl");
    
    props.setProperty("lib.provenance.url",
            this.getExportCommunityUrl() + "/provenance/library.owl");

    if (this.viewerId != null)
        props.setProperty("viewer.id", this.viewerId);
    if (this.userId != null)
        props.setProperty("user.id", this.userId);

    props.setProperty("use_rules", this.getPlannerConfig().useRules() ? "true" : "false");
    return props;
}
 
Example 19
Source File: Domain.java    From wings with Apache License 2.0 4 votes vote down vote up
public Properties getProperties() {
	// Handle legacy domains
	if(this.isLegacy) {
		PropertiesHelper.resetProperties();
		PropertiesHelper.loadWingsProperties(this.domainDirectory + "/wings.properties");
		Properties props = TemplateFactory.createLegacyConfiguration();
		props.putAll(ComponentFactory.createLegacyConfiguration());
		props.putAll(DataFactory.createLegacyConfiguration());
		//props.putAll(ExecutionFactory.createLegacyConfiguration());
		return props;
	}
	
	Properties domainProps = new Properties();
	String domurl = this.domainUrl + usep;
	String domdir = new File(this.domainDirectory).getAbsolutePath() + fsep;
	
	domainProps.setProperty("lib.domain.workflow.url", domurl + this.templateLibrary.getUrl());
	domainProps.setProperty("domain.workflows.dir.url",
			domurl + this.newTemplateDirectory.getUrl());
	
	domainProps.setProperty("lib.domain.execution.url", domurl + this.executionLibrary.getUrl());
	domainProps.setProperty("domain.executions.dir.url",
			domurl + this.newExecutionDirectory.getUrl());
	
	domainProps.setProperty("lib.domain.data.url", domurl + this.dataLibrary.getUrl());
	domainProps.setProperty("ont.domain.data.url", domurl + this.dataOntology.getUrl());
	domainProps
			.setProperty("lib.abstract.url", domurl + this.abstractComponentLibrary.getUrl());
	domainProps
			.setProperty("lib.concrete.url", domurl + this.concreteComponentLibrary.getUrl());
	domainProps.setProperty("ont.domain.component.ns", domurl + this.componentLibraryNamespace);

	domainProps.setProperty("lib.domain.data.storage",
			domdir + this.dataLibrary.getStorageDirectory());
	domainProps.setProperty("lib.domain.code.storage",
			domdir + this.concreteComponentLibrary.getStorageDirectory());

	if (!this.getUseSharedTripleStore()) {
		String furl = "file:";
		domainProps.setProperty("lib.domain.workflow.map",
				furl + domdir + this.templateLibrary.getMapping());
		domainProps.setProperty("domain.workflows.dir.map",
				furl + domdir + this.newTemplateDirectory.getMapping());
		
		domainProps.setProperty("lib.domain.execution.map",
				furl + domdir + this.executionLibrary.getMapping());
		domainProps.setProperty("domain.executions.dir.map",
				furl + domdir + this.newExecutionDirectory.getMapping());
		
		domainProps.setProperty("lib.domain.data.map", 
				furl + domdir + this.dataLibrary.getMapping());
		domainProps.setProperty("ont.domain.data.map", 
				furl + domdir + this.dataOntology.getMapping());
		domainProps.setProperty("lib.abstract.map",
				furl + domdir + this.abstractComponentLibrary.getMapping());
		domainProps.setProperty("lib.concrete.map",
				furl + domdir + this.concreteComponentLibrary.getMapping());
	}
	return domainProps;
}
 
Example 20
Source File: KafkaCache.java    From kcache with Apache License 2.0 4 votes vote down vote up
private void addKafkaCacheConfigsToClientProperties(Properties props) {
    props.putAll(config.originalsWithPrefix("kafkacache."));
}