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

The following examples show how to use java.util.Properties#containsKey() . 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: GobblinServiceJobScheduler.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
private Properties createJobConfig(FlowSpec flowSpec) {
  Properties jobConfig = new Properties();
  Properties flowSpecProperties = flowSpec.getConfigAsProperties();

  jobConfig.putAll(this.properties);
  jobConfig.setProperty(ConfigurationKeys.JOB_NAME_KEY, flowSpec.getUri().toString());
  jobConfig.setProperty(ConfigurationKeys.JOB_GROUP_KEY,
      flowSpec.getConfig().getValue(ConfigurationKeys.FLOW_GROUP_KEY).toString());
  jobConfig.setProperty(ConfigurationKeys.FLOW_RUN_IMMEDIATELY,
      ConfigUtils.getString((flowSpec).getConfig(), ConfigurationKeys.FLOW_RUN_IMMEDIATELY, "false"));

  // todo : we should check if the job schedule is a valid cron schedule
  if (flowSpecProperties.containsKey(ConfigurationKeys.JOB_SCHEDULE_KEY) && StringUtils.isNotBlank(
      flowSpecProperties.getProperty(ConfigurationKeys.JOB_SCHEDULE_KEY))) {
    jobConfig.setProperty(ConfigurationKeys.JOB_SCHEDULE_KEY,
        flowSpecProperties.getProperty(ConfigurationKeys.JOB_SCHEDULE_KEY));
  }

  return jobConfig;
}
 
Example 2
Source File: AuthConfigFactory.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
private AuthConfig getAuthConfigFromOpenShiftConfig(LookupMode lookupMode, Map authConfigMap) throws MojoExecutionException {
    Properties props = System.getProperties();
    String useOpenAuthModeProp = lookupMode.asSysProperty(AUTH_USE_OPENSHIFT_AUTH);
    // Check for system property
    if (props.containsKey(useOpenAuthModeProp)) {
        boolean useOpenShift = Boolean.valueOf(props.getProperty(useOpenAuthModeProp));
        if (useOpenShift) {
            return validateMandatoryOpenShiftLogin(parseOpenShiftConfig(), useOpenAuthModeProp);
        } else {
            return null;
        }
    }

    // Check plugin config
    Map mapToCheck = getAuthConfigMapToCheck(lookupMode,authConfigMap);
    if (mapToCheck != null && mapToCheck.containsKey(AUTH_USE_OPENSHIFT_AUTH) &&
        Boolean.valueOf((String) mapToCheck.get(AUTH_USE_OPENSHIFT_AUTH))) {
            return validateMandatoryOpenShiftLogin(parseOpenShiftConfig(), useOpenAuthModeProp);
    } else {
        return null;
    }
}
 
Example 3
Source File: LoggingConfigDeploymentProcessor.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static boolean isJulConfiguration(final Properties properties) {
    // First check for .levels as it's the cheapest
    if (properties.containsKey(".level")) {
        return true;
        // Check the handlers, in JBoss Log Manager they should be handler.HANDLER_NAME=HANDLER_CLASS,
        // J.U.L. uses fully.qualified.handler.class.property
    } else if (properties.containsKey("handlers")) {
        final String prop = properties.getProperty("handlers", "");
        if (prop != null && !prop.trim().isEmpty()) {
            final String[] handlers = prop.split("\\s*,\\s*");
            for (String handler : handlers) {
                final String key = String.format("handler.%s", handler);
                if (!properties.containsKey(key)) {
                    return true;
                }
            }
        }
    }
    // Assume it's okay
    return false;
}
 
Example 4
Source File: KafkaIngressSpec.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
private static KafkaIngressStartupPosition requireValidStartupPosition(
    KafkaIngressStartupPosition startupPosition, Properties properties) {
  if (startupPosition.isGroupOffsets()
      && !properties.containsKey(ConsumerConfig.GROUP_ID_CONFIG)) {
    throw new IllegalStateException(
        "The ingress is configured to start from committed consumer group offsets in Kafka, but no consumer group id was set.\n"
            + "Please set the group id with the withConsumerGroupId(String) method.");
  }

  return startupPosition;
}
 
Example 5
Source File: PropertyFileAbstractMarker.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
public PropertyFileAbstractMarker(Properties p) throws Exception {
  super("", "", MarkerColors.Aqua);
  if (!p.containsKey(CONDITION) || !p.containsKey(DESCRIPTION) || !p.containsKey(GROUPS) || !p.containsKey(NAME) || !p.containsKey(IGNORE_CASE)) {
    throw new Exception("Not enought parameters");
  }
  this.ignoreCase = Boolean.parseBoolean(p.getProperty(IGNORE_CASE));

  if (ignoreCase) {
    this.condition = p.getProperty(CONDITION).toLowerCase();
  } else {
    this.condition = p.getProperty(CONDITION);
  }

  this.description = p.getProperty(DESCRIPTION);
  this.groups = p.getProperty(GROUPS).split(",");
  for (int i = 0; i < groups.length; i++) {
    groups[i] = groups[i].trim();
  }
  this.name = p.getProperty(NAME);
  this.include = Boolean.parseBoolean(p.getProperty(INCLUDE, "true"));
  this.markerColors = MarkerColors.fromString(p.getProperty(COLOR, ""));
  if (p.containsKey(FILE)) {
    fileName = p.getProperty(FILE);
  }
  test1 = p.getProperty(TEST_STRING_1, "");
  test2 = p.getProperty(TEST_STRING_2, "");
  test3 = p.getProperty(TEST_STRING_3, "");
}
 
Example 6
Source File: GobblinHelixJobLauncher.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Inject in some additional properties
 * @param jobProps job properties
 * @param inputTags list of metadata tags
 * @return
 */
private static List<? extends Tag<?>> addAdditionalMetadataTags(Properties jobProps, List<? extends Tag<?>> inputTags) {
  List<Tag<?>> metadataTags = Lists.newArrayList(inputTags);
  String jobId;

  // generate job id if not already set
  if (jobProps.containsKey(ConfigurationKeys.JOB_ID_KEY)) {
    jobId = jobProps.getProperty(ConfigurationKeys.JOB_ID_KEY);
  } else {
    jobId = JobLauncherUtils.newJobId(JobState.getJobNameFromProps(jobProps));
    jobProps.put(ConfigurationKeys.JOB_ID_KEY, jobId);
  }

  String jobExecutionId = Long.toString(Id.Job.parse(jobId).getSequence());

  // only inject flow tags if a flow name is defined
  if (jobProps.containsKey(ConfigurationKeys.FLOW_NAME_KEY)) {
    metadataTags.add(new Tag<>(TimingEvent.FlowEventConstants.FLOW_GROUP_FIELD,
        jobProps.getProperty(ConfigurationKeys.FLOW_GROUP_KEY, "")));
    metadataTags.add(
        new Tag<>(TimingEvent.FlowEventConstants.FLOW_NAME_FIELD, jobProps.getProperty(ConfigurationKeys.FLOW_NAME_KEY)));

    // use job execution id if flow execution id is not present
    metadataTags.add(new Tag<>(TimingEvent.FlowEventConstants.FLOW_EXECUTION_ID_FIELD,
        jobProps.getProperty(ConfigurationKeys.FLOW_EXECUTION_ID_KEY, jobExecutionId)));
  }

  metadataTags.add(new Tag<>(TimingEvent.FlowEventConstants.JOB_GROUP_FIELD,
      jobProps.getProperty(ConfigurationKeys.JOB_GROUP_KEY, "")));
  metadataTags.add(new Tag<>(TimingEvent.FlowEventConstants.JOB_NAME_FIELD,
      jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY, "")));
  metadataTags.add(new Tag<>(TimingEvent.FlowEventConstants.JOB_EXECUTION_ID_FIELD, jobExecutionId));

  LOGGER.debug("GobblinHelixJobLauncher.addAdditionalMetadataTags: metadataTags {}", metadataTags);

  return metadataTags;
}
 
Example 7
Source File: WADL2UDDI.java    From juddi with Apache License 2.0 5 votes vote down vote up
public WADL2UDDI(UDDIClerk clerk, URLLocalizer urlLocalizer, Properties properties) throws ConfigurationException {
    super();
    this.clerk = clerk;
    this.urlLocalizer = urlLocalizer;
    this.properties = properties;

    if (clerk != null) {
        if (!properties.containsKey("keyDomain")) {
            throw new ConfigurationException("Property keyDomain is a required property when using WADL2UDDI.");
        }
        if (!properties.containsKey("businessKey") && !properties.containsKey("businessName")) {
            throw new ConfigurationException("Either property businessKey, or businessName, is a required property when using WADL2UDDI.");
        }
        if (!properties.containsKey("nodeName")) {
            if (properties.containsKey("serverName") && properties.containsKey("serverPort")) {
                String nodeName = properties.getProperty("serverName") + "_" + properties.getProperty("serverPort");
                properties.setProperty("nodeName", nodeName);
            } else {
                throw new ConfigurationException("Property nodeName is not defined and is a required property when using WADL2UDDI.");
            }
        }
    }

    //Obtaining values from the properties
    this.keyDomainURI = "uddi:" + properties.getProperty("keyDomain") + ":";
    if (properties.contains(Property.BUSINESS_KEY)) {
        this.businessKey = properties.getProperty(Property.BUSINESS_KEY);
    } else {
        //using the BusinessKey Template, and the businessName to construct the key 
        this.businessKey = UDDIKeyConvention.getBusinessKey(properties);
    }
    this.lang = properties.getProperty(Property.LANG, Property.DEFAULT_LANG);
}
 
Example 8
Source File: LdapExtLoginModule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * Logs the specified LDAP env, masking security-sensitive information (passwords).
 * </p>
 *
 * @param env the LDAP env to be logged.
 */
private void traceLDAPEnv(Properties env)
{
   Properties tmp = new Properties();
   tmp.putAll(env);
   if (tmp.containsKey(Context.SECURITY_CREDENTIALS))
      tmp.setProperty(Context.SECURITY_CREDENTIALS, "******");
   if (tmp.containsKey(BIND_CREDENTIAL))
      tmp.setProperty(BIND_CREDENTIAL, "******");
   PicketBoxLogger.LOGGER.traceLDAPConnectionEnv(tmp);
}
 
Example 9
Source File: Stanag4676ImageryChipService.java    From geowave with Apache License 2.0 5 votes vote down vote up
private static String getProperty(final Properties props, final String name) {
  if (System.getProperty(name) != null) {
    return System.getProperty(name);
  } else if (props.containsKey(name)) {
    return props.getProperty(name);
  } else {
    return null;
  }
}
 
Example 10
Source File: ConfigUpdate.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void updateConfig(String config) {
    if (StringUtils.isEmpty(config)) {
        return;
    }
    log.info("update config:{}", config);
    Map<String, Object> configMap = JSONObject.parseObject(config, Map.class);
    if (configMap == null || configMap.isEmpty()) {
        return;
    }

    Properties properties = new Properties();
    for (Map.Entry<String, Object> entry : configMap.entrySet()) {
        if (isConfigIgnore(entry.getKey())) {
            log.info("not first start, ignore config:{}", entry.getKey());
            continue;
        }

        properties.put(entry.getKey(), entry.getValue().toString());
    }
    if (!controller.getBrokerConfig().isRoleConfigInit()) {
        properties.put(ConfigName.ROLE_CONFIG_INIT, "true");
    }
    log.info("properties:{}", properties);

    controller.getConfiguration().update(properties);

    if (properties.containsKey(ConfigName.NAME_SRV_ADDR) && controller.getBrokerOuterAPI() != null) {
        controller.getBrokerOuterAPI().updateNameServerAddressList(controller.getBrokerConfig().getNamesrvAddr());
        log.info("update name srv addr:{}", controller.getBrokerConfig().getNamesrvAddr());
    }
}
 
Example 11
Source File: XACMLProperties.java    From XACML with MIT License 5 votes vote down vote up
/**
 * Clear policy references from a Properties object.
 *
 * @param properties Properties object to clear
 * @param strField Key field
 * @return Properties object passed in
 */
public static Properties clearPolicyProperties(Properties properties, String strField) {
    String policyValue = properties.getProperty(strField);

    String[] policies = policyValue.split("\\s*,\\s*");

    for (String policy : policies) {
        if (properties.containsKey(policy + FILE_APPEND)) {
            properties.remove(policy + FILE_APPEND);
        }
    }

    return properties;
}
 
Example 12
Source File: Hash1Index.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
protected void allocateMemory(Properties properties, int tmpFlag)
    throws StandardException {
  // hash index does not support case-sensitivity setting
  if (properties.containsKey(GfxdConstants.INDEX_CASE_SENSITIVE_PROP)) {
    throw StandardException.newException(
        SQLState.INDEX_CASE_INSENSITIVITY_NOT_SUPPORTED,
        "primary key constraint");
  }
}
 
Example 13
Source File: WatermarkDatasetVersionFinder.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public static Properties convertDeprecatedProperties(Properties props) {
  if (props.containsKey(DEPRECATED_WATERMARK_REGEX_KEY)) {
    log.info(String.format("Found deprecated key %s. Replacing it with %s", DEPRECATED_WATERMARK_REGEX_KEY,
        org.apache.gobblin.data.management.version.finder.WatermarkDatasetVersionFinder.WATERMARK_REGEX_KEY));

    props.setProperty(org.apache.gobblin.data.management.version.finder.WatermarkDatasetVersionFinder.WATERMARK_REGEX_KEY,
        props.getProperty(DEPRECATED_WATERMARK_REGEX_KEY));
    props.remove(DEPRECATED_WATERMARK_REGEX_KEY);
  }

  return props;
}
 
Example 14
Source File: PersistS3.java    From h2o-2 with Apache License 2.0 5 votes vote down vote up
static ClientConfiguration s3ClientCfg() {
  ClientConfiguration cfg = new ClientConfiguration();
  Properties prop = System.getProperties();
  if( prop.containsKey(S3_SOCKET_TIMEOUT_PROP) ) cfg.setSocketTimeout(Integer.getInteger(S3_SOCKET_TIMEOUT_PROP));
  if( prop.containsKey(S3_CONNECTION_TIMEOUT_PROP) ) cfg.setConnectionTimeout(Integer
      .getInteger(S3_CONNECTION_TIMEOUT_PROP));
  if( prop.containsKey(S3_MAX_ERROR_RETRY_PROP) ) cfg.setMaxErrorRetry(Integer.getInteger(S3_MAX_ERROR_RETRY_PROP));
  if( prop.containsKey(S3_MAX_HTTP_CONNECTIONS_PROP) ) cfg.setMaxConnections(Integer
      .getInteger(S3_MAX_HTTP_CONNECTIONS_PROP));
  cfg.setProtocol(Protocol.HTTP);
  return cfg;
}
 
Example 15
Source File: HiveAvroORCQueryGenerator.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private static Properties getTableProperties(Properties tableProperties) {
  if (null == tableProperties || tableProperties.size() == 0) {
    return (Properties) DEFAULT_TBL_PROPERTIES.clone();
  }

  for (String property : DEFAULT_TBL_PROPERTIES.stringPropertyNames()) {
    if (!tableProperties.containsKey(property)) {
      tableProperties.put(property, DEFAULT_TBL_PROPERTIES.get(property));
    }
  }

  return tableProperties;
}
 
Example 16
Source File: Configuration.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Checks for the presence of the property <code>name</code> in the
 * deprecation map. Returns the first of the list of new keys if present
 * in the deprecation map or the <code>name</code> itself. If the property
 * is not presently set but the property map contains an entry for the
 * deprecated key, the value of the deprecated key is set as the value for
 * the provided property name.
 *
 * @param deprecations deprecation context
 * @param name the property name
 * @return the first property in the list of properties mapping
 *         the <code>name</code> or the <code>name</code> itself.
 */
private String[] handleDeprecation(DeprecationContext deprecations,
                                   String name) {
	if (null != name) {
		name = name.trim();
	}
	// Initialize the return value with requested name
	String[] names = new String[]{name};
	// Deprecated keys are logged once and an updated names are returned
	DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(name);
	if (keyInfo != null) {
		if (!keyInfo.getAndSetAccessed()) {
			logDeprecation(keyInfo.getWarningMessage(name));
		}
		// Override return value for deprecated keys
		names = keyInfo.newKeys;
	}
	// If there are no overlay values we can return early
	Properties overlayProperties = getOverlay();
	if (overlayProperties.isEmpty()) {
		return names;
	}
	// Update properties and overlays with reverse lookup values
	for (String n : names) {
		String deprecatedKey = deprecations.getReverseDeprecatedKeyMap().get(n);
		if (deprecatedKey != null && !overlayProperties.containsKey(n)) {
			String deprecatedValue = overlayProperties.getProperty(deprecatedKey);
			if (deprecatedValue != null) {
				getProps().setProperty(n, deprecatedValue);
				overlayProperties.setProperty(n, deprecatedValue);
			}
		}
	}
	return names;
}
 
Example 17
Source File: StandaloneStreamUpdateHandler.java    From warp10-platform with Apache License 2.0 4 votes vote down vote up
public StandaloneStreamUpdateHandler(KeyStore keystore, Properties properties, StandaloneDirectoryClient directoryClient, StoreClient storeClient) {
  super(StandaloneStreamUpdateWebSocket.class);

  this.keyStore = keystore;
  
  this.classKeyLongs = SipHashInline.getKey(this.keyStore.getKey(KeyStore.SIPHASH_CLASS));    
  this.labelsKeyLongs = SipHashInline.getKey(this.keyStore.getKey(KeyStore.SIPHASH_LABELS));

  this.storeClient = storeClient;
  this.directoryClient = directoryClient;
  this.properties = properties;
  this.updateActivity = "true".equals(properties.getProperty(Configuration.INGRESS_ACTIVITY_UPDATE));

  this.maxValueSize = Long.parseLong(properties.getProperty(Configuration.STANDALONE_VALUE_MAXSIZE, StandaloneIngressHandler.DEFAULT_VALUE_MAXSIZE));
  
  this.parseAttributes = "true".equals(properties.getProperty(Configuration.INGRESS_PARSE_ATTRIBUTES));
  this.allowDeltaAttributes = "true".equals(WarpConfig.getProperty(Configuration.INGRESS_ATTRIBUTES_ALLOWDELTA));

  if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_DEFAULT)) {
    this.maxpastDefault = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_DEFAULT));
    if (this.maxpastDefault < 0) {
      throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXPAST_DEFAULT + "' MUST be positive.");
    }
  } else {
    this.maxpastDefault = null;
  }
  
  if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_DEFAULT)) {
    this.maxfutureDefault = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_DEFAULT));
    if (this.maxfutureDefault < 0) {
      throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXFUTURE_DEFAULT + "' MUST be positive.");
    }
  } else {
    this.maxfutureDefault = null;
  }

  if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_OVERRIDE)) {
    this.maxpastOverride = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXPAST_OVERRIDE));
    if (this.maxpastOverride < 0) {
      throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXPAST_OVERRIDE + "' MUST be positive.");
    }
  } else {
    this.maxpastOverride = null;
  }
  
  if (null != WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_OVERRIDE)) {
    this.maxfutureOverride = Long.parseLong(WarpConfig.getProperty(Configuration.INGRESS_MAXFUTURE_OVERRIDE));
    if (this.maxfutureOverride < 0) {
      throw new RuntimeException("Value of '" + Configuration.INGRESS_MAXFUTURE_OVERRIDE + "' MUST be positive.");
    }
  } else {
    this.maxfutureOverride = null;
  }
  
  this.ignoreOutOfRange = "true".equals(WarpConfig.getProperty(Configuration.INGRESS_OUTOFRANGE_IGNORE));
  
  if ("false".equals(properties.getProperty(Configuration.DATALOG_LOGSHARDKEY))) {
    logShardKey = false;
  } else {
    logShardKey = true;
  }

  if (properties.containsKey(Configuration.DATALOG_DIR)) {
    File dir = new File(properties.getProperty(Configuration.DATALOG_DIR));
    
    if (!dir.exists()) {
      throw new RuntimeException("Data logging target '" + dir + "' does not exist.");
    } else if (!dir.isDirectory()) {
      throw new RuntimeException("Data logging target '" + dir + "' is not a directory.");
    } else {
      loggingDir = dir;
      LOG.info("Data logging enabled in directory '" + dir + "'.");
    }
    
    String id = properties.getProperty(Configuration.DATALOG_ID);
    
    if (null == id) {
      throw new RuntimeException("Property '" + Configuration.DATALOG_ID + "' MUST be set to a unique value for this instance.");
    } else {
      datalogId = new String(OrderPreservingBase64.encode(id.getBytes(StandardCharsets.UTF_8)), StandardCharsets.US_ASCII);
    }
    
  } else {
    loggingDir = null;
    datalogId = null;
  }

  this.datalogSync = "true".equals(WarpConfig.getProperty(Configuration.DATALOG_SYNC));
  if (properties.containsKey(Configuration.DATALOG_PSK)) {
    this.datalogPSK = this.keyStore.decodeKey(properties.getProperty(Configuration.DATALOG_PSK));
  } else {
    this.datalogPSK = null;
  }    
}
 
Example 18
Source File: PgSessionBuilder.java    From pgadba with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Parses the postgresql connection url that the user supplies to the library.
 * @param url url string
 * @param defaults the default values that's used if the user doesn't override them
 * @return a map of properties
 */
public static Map<SessionProperty, Object> parseUrl(String url, Properties defaults) {
  Map<SessionProperty, Object> urlProps = new HashMap<>();

  String urlServer = url;
  String urlArgs = "";

  int qPos = url.indexOf('?');
  if (qPos != -1) {
    urlServer = url.substring(0, qPos);
    urlArgs = url.substring(qPos + 1);
  }

  if (!urlServer.startsWith("jdbc:postgresql:")) {
    return null;
  }
  urlServer = urlServer.substring("jdbc:postgresql:".length());

  if (urlServer.startsWith("//")) {
    urlServer = urlServer.substring(2);
    int slash = urlServer.indexOf('/');
    if (slash == -1) {
      return null;
    }
    urlProps.put(PgSessionProperty.DATABASE,
        URLDecoder.decode(urlServer.substring(slash + 1), StandardCharsets.UTF_8));

    String[] addresses = urlServer.substring(0, slash).split(",");
    StringBuilder hosts = new StringBuilder();
    StringBuilder ports = new StringBuilder();
    for (String address : addresses) {
      int portIdx = address.lastIndexOf(':');
      if (portIdx != -1 && address.lastIndexOf(']') < portIdx) {
        String portStr = address.substring(portIdx + 1);
        try {
          // squid:S2201 The return value of "parseInt" must be used.
          // The side effect is NumberFormatException, thus ignore sonar error here
          Integer.parseInt(portStr); // NOSONAR
        } catch (NumberFormatException ex) {
          return null;
        }
        ports.append(portStr);
        hosts.append(address.subSequence(0, portIdx));
      } else {
        ports.append("5432");
        hosts.append(address);
      }
      ports.append(',');
      hosts.append(',');
    }
    ports.setLength(ports.length() - 1);
    hosts.setLength(hosts.length() - 1);
    urlProps.put(PgSessionProperty.PORT, Integer.parseInt(ports.toString()));
    urlProps.put(PgSessionProperty.HOST, hosts.toString());
  } else {
    /*
     * if there are no defaults set or any one of PORT, HOST, DBNAME not set then
     * set it to default
     */
    if (defaults == null || !defaults.containsKey(PgSessionProperty.PORT.name())) {
      urlProps.put(PgSessionProperty.PORT, 5432);
    }
    if (defaults == null || !defaults.containsKey(PgSessionProperty.HOST.name())) {
      urlProps.put(PgSessionProperty.HOST, "localhost");
    }
    if (defaults == null || !defaults.containsKey(PgSessionProperty.DATABASE.name())) {
      urlProps.put(PgSessionProperty.DATABASE, URLDecoder.decode(urlServer, StandardCharsets.UTF_8));
    }
  }

  // parse the args part of the url
  String[] args = urlArgs.split("&");
  for (String token : args) {
    if (token.isEmpty()) {
      continue;
    }
    int pos = token.indexOf('=');
    if (pos == -1) {
      urlProps.put(PgSessionProperty.lookup(token), "");
    } else {
      urlProps.put(PgSessionProperty.lookup(token.substring(0, pos)),
          URLDecoder.decode(token.substring(pos + 1), StandardCharsets.UTF_8));
    }
  }

  return urlProps;
}
 
Example 19
Source File: Utils.java    From luxun with Apache License 2.0 4 votes vote down vote up
public static String getString(Properties props, String name) {
    if (props.containsKey(name)) {
        return props.getProperty(name);
    }
    throw new IllegalArgumentException("Missing required property '" + name + "'");
}
 
Example 20
Source File: Instructions.java    From wisdom with Apache License 2.0 3 votes vote down vote up
/**
 * Utility method to merge instructions from {@code props2} into the {@code props1}. The instructions
 * from {@code props2} do not override the instructions  from {@code props1} (when both contain the same
 * instruction), so instructions from {@code props1} stay unchanged and are contained in the file set of
 * instructions.
 * <p>
 * Notice that entries with empty values from {@code props2} are <strong>not</strong> merged.
 *
 * @param props1 the first set of instructions
 * @param props2 the second set of instructions
 * @return the new set of instructions containing the instructions from {@code props2} merged into {@code props1}.
 */
public static Properties mergeAndSkipExisting(Properties props1, Properties props2) {
    Properties properties = new Properties();
    properties.putAll(props1);
    for (String key : props2.stringPropertyNames()) {
        if (!props1.containsKey(key) && !Strings.isNullOrEmpty(props2.getProperty(key))) {
            properties.put(key, props2.getProperty(key));
        }
    }
    return properties;
}