/* (non-Javadoc)
@see net.roboconf.target.api.AbstractThreadedTargetHandler
#machineConfigurator(net.roboconf.target.api.TargetHandlerParameters, java.lang.String)
428724
@Override
	public MachineConfigurator machineConfigurator( TargetHandlerParameters parameters, String machineId )
	throws TargetException {

		// Configure the machine only if there is an IP address
		MachineConfigurator configurator = null;

		// Retrieve the IP address
		String ip = this.machineIdToIp.get( machineId );
		if( ! Utils.isEmptyOrWhitespaces(ip)) {
			configurator = new ConfiguratorOnCreation( parameters, ip, machineId, this );
		}

		return configurator;
	}
46976
protected void configureMethodArgs(Injector injector) {

        Class<?>[] types = method.getParameterTypes();
        extractors = new ArgumentExtractor[types.length];
        patterns = new String[types.length];
        for (int i = 0; i < types.length; i++) {
            final Parameter parameter = method.getParameters()[i];
            final Class<? extends Collection> collectionType;
            final Class<?> objectType;
            if (Collection.class.isAssignableFrom(types[i])) {
                collectionType = (Class<? extends Collection>) types[i];
                objectType = getParameterGenericType(parameter);
            } else {
                collectionType = null;
                objectType = types[i];
            }

            // determine the appropriate extractor
            Class<? extends ArgumentExtractor> extractorType;
            if (FileItem.class == objectType) {
                extractorType = FileItemExtractor.class;
            } else {
                extractorType = ControllerUtil.getArgumentExtractor(parameter);
            }

            // instantiate the extractor
            extractors[i] = injector.getInstance(extractorType);

            // configure the extractor
            if (extractors[i] instanceof ConfigurableExtractor<?>) {
                ConfigurableExtractor extractor = (ConfigurableExtractor) extractors[i];
                Annotation annotation = ClassUtil.getAnnotation(parameter, extractor.getAnnotationClass());
                if (annotation != null) {
                    extractor.configure(annotation);
                }
            }

            if (extractors[i] instanceof SuffixExtractor) {
                // the last parameter can be assigned content type suffixes
                SuffixExtractor extractor = (SuffixExtractor) extractors[i];
                extractor.setSuffixes(contentTypeSuffixes);
            }

            if (collectionType != null) {
                if (extractors[i] instanceof CollectionExtractor) {
                    CollectionExtractor extractor = (CollectionExtractor) extractors[i];
                    extractor.setCollectionType(collectionType);
                } else {
                    throw new FatalException(
                            "Controller method '{}' parameter {} of type '{}' does not specify an argument extractor that supports collections!",
                            Util.toString(method), i + 1, Util.toString(collectionType, objectType));
                }
            }

            if (extractors[i] instanceof TypedExtractor) {
                TypedExtractor extractor = (TypedExtractor) extractors[i];
                extractor.setObjectType(objectType);
            }

            if (extractors[i] instanceof NamedExtractor) {
                // ensure that the extractor has a proper name
                NamedExtractor namedExtractor = (NamedExtractor) extractors[i];
                if (Strings.isNullOrEmpty(namedExtractor.getName())) {
                    // parameter is not named via annotation
                    // try looking for the parameter name in the compiled .class file
                    if (parameter.isNamePresent()) {
                        namedExtractor.setName(parameter.getName());
                    } else {
                        log.error("Properly annotate your controller methods OR specify the '-parameters' flag for your Java compiler!");
                        throw new FatalException(
                                "Controller method '{}' parameter {} of type '{}' does not specify a name!",
                                Util.toString(method), i + 1, Util.toString(collectionType, objectType));
                    }
                }
            }
        }
    }
256242
@Override
	public MachineConfigurator machineConfigurator( TargetHandlerParameters parameters, String machineId ) {
		return new OpenstackMachineConfigurator(
				parameters.getTargetProperties(),
				machineId,
				parameters.getApplicationName(),
				parameters.getScopedInstance());
	}
523571
protected void setConfigurationProvider(ConfigurationProvider p) {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "setConfigurationProvider", p);

        try {
            ConfigurationProviderManager.setConfigurationProvider(p);

            // in an osgi environment we may get unconfigured and then reconfigured as bundles are
            // started/stopped.  If we were previously unconfigured, then we would have shutdown and
            // our state will be 'stopped' (rather than inactive).  If so, then re-start now.
            // The alternative would perhaps be to modify the checkTMState method to re-start for this state?
            if (_state == TMService.TMStates.STOPPED) {
                start();
            }
        } catch (Exception e) {
            FFDCFilter.processException(e, "com.ibm.tx.jta.util.impl.TxTMHelper.setConfigurationProvider", "37", this);
        }
        if (tc.isEntryEnabled())
            Tr.exit(tc, "setConfigurationProvider");
    }
271484
@Override
	public void configure(Configuration parameters) {
		super.configure(parameters);
		
		String delimString = parameters.getString(RECORD_DELIMITER, null);
		if (delimString != null) {
			String charsetName = parameters.getString(RECORD_DELIMITER_ENCODING, null);

			if (charsetName == null) {
				setDelimiter(delimString);
			} else {
				try {
					setDelimiter(delimString, charsetName);
				}
				catch (UnsupportedCharsetException e) {
					throw new IllegalArgumentException("The charset with the name '" + charsetName + 
							"' is not supported on this TaskManager instance.", e);
				}
			}
		}
		
		// set the number of samples
		String samplesString = parameters.getString(NUM_STATISTICS_SAMPLES, null);
		if (samplesString != null) {
			try {
				setNumLineSamples(Integer.parseInt(samplesString));
			}
			catch (NumberFormatException e) {
				if (LOG.isWarnEnabled()) {
					LOG.warn("Invalid value for number of samples to take: " + samplesString + ". Skipping sampling.");
				}
				setNumLineSamples(0);
			}
		}
	}
1249778
public void setNameGenerator(I_CmsFileNameGenerator nameGenerator) throws CmsConfigurationException {

        if (m_frozen) {
            throw new CmsConfigurationException(Messages.get().container(Messages.ERR_NO_CONFIG_AFTER_STARTUP_0));
        }
        m_nameGenerator = nameGenerator;
    }
246093
@Override
	public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
	throws TargetException {
		// TODO remove next line when APIs get compatible...
		String postfix = (parameters.getTargetProperties().get(CloudautomationMixins.PROVIDER_ENDPOINT) != null ? "" : "/compute");
		return OcciVMUtils.isVMRunning(parameters.getTargetProperties().get(SERVER_IP_PORT) + postfix, machineId);
	}
132063
public static IdGenerator newFlakeIdGenerator(MachineIdProvider machineIdProvider) {
        EncodingProvider encodingProvider = new FlakeEncodingProvider(machineIdProvider.getMachineId());
        return new DefaultIdGenerator(new SystemTimeProvider(), encodingProvider);
    }
173142
protected void configureParser(LSParser parser) {
        for (Map.Entry<String, Object> setting : parseSettings.entrySet()) {
            setParserConfigParameter(parser, setting.getKey(), setting.getValue());
        }
    }
984888
protected String acquireIpAddress( TargetHandlerParameters parameters, String machineId ) {

		// Load IP addresses on demand (that's the case if we are in this method).
		// This implementation is compliant with a same IP address being used in
		// several "target.properties" files.
		String result = null;
		String ips = parameters.getTargetProperties().get( IP_ADDRESSES );
		ips = ips == null ? "" : ips;
		for( String ip : Utils.splitNicely( ips, "," )) {
			if( Utils.isEmptyOrWhitespaces( ip ))
				continue;

			if( this.usedIps.putIfAbsent( ip, 1 ) == null ) {
				this.machineIdToIp.put( machineId, ip );
				result = ip;
				save( this );
				break;
			}
		}

		return result;
	}
1087671
public static IdGenerator newSnowflakeIdGenerator(MachineIdProvider machineIdProvider) {
        EncodingProvider encodingProvider = new SnowflakeEncodingProvider(machineIdProvider.getMachineId());
        return new DefaultIdGenerator(new SystemTimeProvider(), encodingProvider);
    }
281347
@Override
	public String createMachine( TargetHandlerParameters parameters ) throws TargetException {

		this.logger.fine( "Creating a new machine on AWS." );

		// For IaaS, we only expect root instance names to be passed
		if( InstanceHelpers.countInstances( parameters.getScopedInstancePath()) > 1 )
			throw new TargetException( "Only root instances can be passed in arguments." );

		String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath());

		// Deal with the creation
		String instanceId;
		try {
			AmazonEC2 ec2 = createEc2Client( parameters.getTargetProperties());
			String userData = UserDataHelpers.writeUserDataAsString(
					parameters.getMessagingProperties(),
					parameters.getDomain(),
					parameters.getApplicationName(),
					rootInstanceName );

			RunInstancesRequest runInstancesRequest = prepareEC2RequestNode( parameters.getTargetProperties(), userData );
			RunInstancesResult runInstanceResult = ec2.runInstances( runInstancesRequest );
			instanceId = runInstanceResult.getReservation().getInstances().get( 0 ).getInstanceId();

		} catch( Exception e ) {
			this.logger.severe( "An error occurred while creating a new machine on EC2. " + e.getMessage());
			throw new TargetException( e );
		}

		return instanceId;
	}
211843
@Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        BugsnagScheduledTaskExceptionHandler bugsnagErrorHandler =
                new BugsnagScheduledTaskExceptionHandler(bugsnag);

        // Decision process for finding a TaskScheduler, in order of preference:
        //
        // 1. use the scheduler from the task registrar
        // 2. search for a TaskScheduler bean, by type, then by name
        // 3. search for a ScheduledExecutorService bean by type, then by name,
        //    and wrap it in a TaskScheduler
        // 4. create our own TaskScheduler

        TaskScheduler registrarScheduler = taskRegistrar.getScheduler();
        TaskScheduler taskScheduler = registrarScheduler != null
                ? registrarScheduler : beanLocator.resolveTaskScheduler();

        if (taskScheduler != null) {
            configureExistingTaskScheduler(taskScheduler, bugsnagErrorHandler);
        } else {
            ScheduledExecutorService executorService
                    = beanLocator.resolveScheduledExecutorService();
            taskScheduler = createNewTaskScheduler(executorService, bugsnagErrorHandler);
            taskRegistrar.setScheduler(taskScheduler);
        }
    }
637895
@VisibleForTesting
  public static int getConfImpl(Supplier<RetryHandlingMetaMasterConfigClient> clientSupplier,
      AlluxioConfiguration alluxioConf, String... args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
      cmd = parser.parse(OPTIONS, args, true /* stopAtNonOption */);
    } catch (ParseException e) {
      printHelp("Unable to parse input args: " + e.getMessage());
      return 1;
    }
    args = cmd.getArgs();

    Map<String, ConfigProperty> confMap = new HashMap<>();
    if (cmd.hasOption(MASTER_OPTION_NAME)) {
      // load cluster-wide configuration
      try (RetryHandlingMetaMasterConfigClient client = clientSupplier.get()) {
        client.getConfiguration().getClusterConf().forEach(
            prop -> confMap.put(prop.getName(), prop.toProto()));
      } catch (IOException e) {
        System.out.println("Unable to get master-side configuration: " + e.getMessage());
        return -1;
      }
    } else {
      // load local configuration
      for (PropertyKey key : alluxioConf.keySet()) {
        if (key.isBuiltIn()) {
          ConfigProperty.Builder config = ConfigProperty.newBuilder().setName(key.getName())
              .setSource(alluxioConf.getSource(key).toString());
          String val = alluxioConf.getOrDefault(key, null,
              ConfigurationValueOptions.defaults().useDisplayValue(true));
          if (val != null) {
            config.setValue(val);
          }
          confMap.put(key.getName(), config.build());
        }
      }
    }

    StringBuilder output = new StringBuilder();
    switch (args.length) {
      case 0:
        List<ConfigProperty> properties = new ArrayList<>(confMap.values());
        properties.sort(Comparator.comparing(ConfigProperty::getName));
        for (ConfigProperty property : properties) {
          String value = ConfigurationUtils.valueAsString(property.getValue());
          output.append(String.format("%s=%s", property.getName(), value));
          if (cmd.hasOption(SOURCE_OPTION_NAME)) {
            output.append(String.format(" (%s)", property.getSource()));
          }
          output.append("\n");
        }
        System.out.print(output.toString());
        break;
      case 1:
        if (!PropertyKey.isValid(args[0])) {
          printHelp(String.format("%s is not a valid configuration key", args[0]));
          return 1;
        }
        // args[0] can be the alias
        String key = PropertyKey.fromString(args[0]).getName();
        ConfigProperty property = confMap.get(key);
        if (property == null) {
          printHelp(String.format("%s is not found", key));
          return 1;
        }

        if (property.getValue() == null) {
          // value not set
          System.out.println("");
        } else {
          if (cmd.hasOption(SOURCE_OPTION_NAME)) {
            System.out.println(property.getSource());
          } else if (cmd.hasOption(UNIT_OPTION_NAME)) {
            String arg = cmd.getOptionValue(UNIT_OPTION_NAME).toUpperCase();
            try {
              ByteUnit byteUnit;
              byteUnit = ByteUnit.valueOf(arg);
              System.out.println(
                  FormatUtils.parseSpaceSize(property.getValue()) / byteUnit.getValue());
              break;
            } catch (Exception e) {
              // try next unit parse
            }
            try {
              TimeUnit timeUnit;
              timeUnit = TimeUnit.valueOf(arg);
              System.out.println(
                  FormatUtils.parseTimeSize(property.getValue()) / timeUnit.getValue());
              break;
            } catch (IllegalArgumentException ex) {
              // try next unit parse
            }
            printHelp(String.format("%s is not a valid unit", arg));
            return 1;
          } else {
            System.out.println(property.getValue());
          }
        }
        break;
      default:
        printHelp(String.format("More arguments than expected. Args: %s", Arrays.toString(args)));
        return 1;
    }
    return 0;
  }
1299153
public static SslProvider addHandlerConfigurator(
			SslProvider provider, Consumer<? super SslHandler> handlerConfigurator) {
		Objects.requireNonNull(provider, "provider");
		Objects.requireNonNull(handlerConfigurator, "handlerConfigurator");
		return new SslProvider(provider, handlerConfigurator);
	}
577537
@Override
	public ObjectMapper configureObjectMapper(ObjectMapper mapper) {

		mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		mapper.registerModule(new Jackson2HalFormsModule());
		mapper.setHandlerInstantiator(new Jackson2HalFormsModule.HalFormsHandlerInstantiator(relProvider,
				curieProvider.getIfAvailable(() -> CurieProvider.NONE), messageSourceAccessor, true,
				halFormsConfiguration.getIfAvailable(HalFormsConfiguration::new)));

		return mapper;
	}
1110851
public static HashMap<String, MtasConfiguration> readMtasTokenizerConfigurations(
      ResourceLoader resourceLoader, String configFile) throws IOException {
    HashMap<String, HashMap<String, String>> configs = readConfigurations(
        resourceLoader, configFile, MtasTokenizerFactory.class.getName());
    if (configs == null) {
      throw new IOException("no configurations");
    } else {
      HashMap<String, MtasConfiguration> result = new HashMap<String, MtasConfiguration>();
      for (Entry<String, HashMap<String, String>> entry : configs.entrySet()) {
        HashMap<String, String> config = entry.getValue();
        if (config.containsKey(TOKENIZER_CONFIGURATION_FILE)) {
          result.put(entry.getKey(), readConfiguration(resourceLoader
              .openResource(config.get(TOKENIZER_CONFIGURATION_FILE))));
        } else {
          throw new IOException("configuration " + entry.getKey() + " has no "
              + TOKENIZER_CONFIGURATION_FILE);
        }
      }
      return result;
    }
  }