Example usage for org.apache.commons.configuration Configuration getInt

List of usage examples for org.apache.commons.configuration Configuration getInt

Introduction

In this page you can find the example usage for org.apache.commons.configuration Configuration getInt.

Prototype

int getInt(String key, int defaultValue);

Source Link

Document

Get a int associated with the given configuration key.

Usage

From source file:edu.cwru.sepia.model.BestEffortModel.java

public BestEffortModel(State init, StateCreator restartTactic, Configuration configuration) {
    super(init, restartTactic, configuration, Logger.getLogger(BestEffortModel.class.getCanonicalName()));
    this.numAttempts = configuration.getInt(NUM_ATTEMPTS, 2);
}

From source file:com.appeligo.alerts.KeywordAlertThread.java

public KeywordAlertThread(Configuration config) throws IOException {
    super("KeywordAlertThread");
    isActive = true;/*from w w w . ja  va2 s  .  c o  m*/
    alertManager = AlertManager.getInstance();
    liveIndexDir = config.getString("luceneLiveIndex");
    liveLineup = config.getString("liveLineup");
    maxConsecutiveExceptions = config.getInt("maxConsecutiveExceptions", 10);
    shortestTimeBetweenQueriesMs = config.getLong("shortestTimeBetweenQueriesMs",
            DEFAULT_SHORTEST_TIME_BETWEEN_QUERIES_MS);
    keywordAlertProximity = config.getInt("keywordAlertProximity", 10);
    if (!IndexReader.indexExists(liveIndexDir)) {
        log.error("Lucene Live Index is missing or invalid at " + liveIndexDir
                + ". Trying anyway in case this gets resolved.");
    }
    parser = new QueryParser("text", new PorterStemAnalyzer(LuceneIndexer.STOP_WORDS));
    parser.setDefaultOperator(Operator.AND);
    helper = new KeywordAlertChecker(config);
}

From source file:net.sf.jclal.evaluation.method.kFoldCrossValidation.java

/**
 * @param configuration The configuration of K-Fold cross validation.
 *The XML labels supported are:// w  ww  .  jav a2 s .c  om
 *
 * <ul>
 * <li><b>stratify= boolean</b></li>
 * <li><b>num-folds= int</b></li>
 * </ul>
 */
@Override
public void configure(Configuration configuration) {
    super.configure(configuration);

    // Set stratify (default false)
    boolean stratifyValue = configuration.getBoolean("stratify", stratify);
    setStratify(stratifyValue);

    // num folds
    int numFols = configuration.getInt("num-folds", numFolds);
    if (numFols < 1) {
        throw new ConfigurationRuntimeException("\n<num-folds>" + numFols + "</num-folds>. " + "num-folds > 0");
    }
    setNumFolds(numFols);
}

From source file:com.yahoo.ads.pb.PistachiosServer.java

public PistachiosServer() {
    Configuration conf = ConfigurationManager.getConfiguration();

    int numBatchThread = conf.getInt("Profile.Process.Number.Batch.Thread", 64);

    logger.info("numBatchThread=", numBatchThread);

    ExecutorService executorService = Executors.newFixedThreadPool(numBatchThread);
    executorService.execute(new Runnable() {
        @Override//  www  .  j a  v a2s.  c  om
        public void run() {
            while (true) {
                logger.info("before process synchronousQueue.size()=", synchronousQueue.size());
                try {
                    PistachiosMessage message = synchronousQueue.take();
                    instance.handler.process(message.partition, ByteBuffer.wrap(message.value));
                    logger.info("after process synchronousQueue.size()=", synchronousQueue.size());
                } catch (NoSuchElementException e) {
                    logger.info("error: {}", e);
                } catch (InterruptedException e) {
                    logger.info("error: {}", e);
                } catch (TException e) {
                    logger.info("error: {}", e);
                }
            }
        }
    });

    // executorService.shutdown();
}

From source file:com.cisco.oss.foundation.http.netlifx.netty.NettyNetflixHttpClient.java

private InternalServerProxyMetadata loadServersMetadataConfiguration() {

    Configuration subset = ConfigurationFactory.getConfiguration().subset(getApiName());
    final Iterator<String> keysIterator = subset.getKeys();

    // read default values
    int readTimeout = subset.getInt("http." + LoadBalancerConstants.READ_TIME_OUT,
            LoadBalancerConstants.DEFAULT_READ_TIMEOUT);
    int connectTimeout = subset.getInt("http." + LoadBalancerConstants.CONNECT_TIME_OUT,
            LoadBalancerConstants.DEFAULT_CONNECT_TIMEOUT);
    long waitingTime = subset.getLong("http." + LoadBalancerConstants.WAITING_TIME,
            LoadBalancerConstants.DEFAULT_WAITING_TIME);
    int numberOfAttempts = subset.getInt("http." + LoadBalancerConstants.NUMBER_OF_ATTEMPTS,
            LoadBalancerConstants.DEFAULT_NUMBER_OF_ATTEMPTS);
    long retryDelay = subset.getLong("http." + LoadBalancerConstants.RETRY_DELAY,
            LoadBalancerConstants.DEFAULT_RETRY_DELAY);

    long idleTimeout = subset.getLong("http." + LoadBalancerConstants.IDLE_TIME_OUT,
            LoadBalancerConstants.DEFAULT_IDLE_TIMEOUT);
    int maxConnectionsPerAddress = subset.getInt("http." + LoadBalancerConstants.MAX_CONNECTIONS_PER_ADDRESS,
            LoadBalancerConstants.DEFAULT_MAX_CONNECTIONS_PER_ADDRESS);
    int maxConnectionsTotal = subset.getInt("http." + LoadBalancerConstants.MAX_CONNECTIONS_TOTAL,
            LoadBalancerConstants.DEFAULT_MAX_CONNECTIONS_TOTAL);
    int maxQueueSizePerAddress = subset.getInt("http." + LoadBalancerConstants.MAX_QUEUE_PER_ADDRESS,
            LoadBalancerConstants.DEFAULT_MAX_QUEUE_PER_ADDRESS);
    boolean followRedirects = subset.getBoolean("http." + LoadBalancerConstants.FOLLOW_REDIRECTS, false);
    boolean disableCookies = subset.getBoolean("http." + LoadBalancerConstants.DISABLE_COOKIES, false);
    boolean autoCloseable = subset.getBoolean("http." + LoadBalancerConstants.AUTO_CLOSEABLE, true);
    boolean autoEncodeUri = subset.getBoolean("http." + LoadBalancerConstants.AUTO_ENCODE_URI, true);
    boolean staleConnectionCheckEnabled = subset
            .getBoolean("http." + LoadBalancerConstants.IS_STALE_CONN_CHECK_ENABLED, false);
    boolean serviceDirectoryEnabled = subset
            .getBoolean("http." + LoadBalancerConstants.SERVICE_DIRECTORY_IS_ENABLED, false);
    String serviceName = subset.getString("http." + LoadBalancerConstants.SERVICE_DIRECTORY_SERVICE_NAME,
            "UNKNOWN");

    String keyStorePath = subset.getString("http." + LoadBalancerConstants.KEYSTORE_PATH, "");
    String keyStorePassword = subset.getString("http." + LoadBalancerConstants.KEYSTORE_PASSWORD, "");
    String trustStorePath = subset.getString("http." + LoadBalancerConstants.TRUSTSTORE_PATH, "");
    String trustStorePassword = subset.getString("http." + LoadBalancerConstants.TRUSTSTORE_PASSWORD, "");
    startEurekaClient = subset.getBoolean("http.startEurekaClient", true);

    final List<String> keys = new ArrayList<String>();

    while (keysIterator.hasNext()) {
        String key = keysIterator.next();
        keys.add(key);//from ww  w. j av  a  2 s.com
    }

    Collections.sort(keys);

    List<Pair<String, Integer>> hostAndPortPairs = new CopyOnWriteArrayList<Pair<String, Integer>>();

    for (String key : keys) {

        if (key.contains(LoadBalancerConstants.HOST)) {

            String host = subset.getString(key);

            // trim the host name
            if (org.apache.commons.lang.StringUtils.isNotEmpty(host)) {
                host = host.trim();
            }
            final String portKey = key.replace(LoadBalancerConstants.HOST, LoadBalancerConstants.PORT);
            if (subset.containsKey(portKey)) {
                int port = subset.getInt(portKey);
                // save host and port for future creation of server list
                hostAndPortPairs.add(Pair.of(host, port));
            }
        }

    }

    InternalServerProxyMetadata metadata = new InternalServerProxyMetadata(readTimeout, connectTimeout,
            idleTimeout, maxConnectionsPerAddress, maxConnectionsTotal, maxQueueSizePerAddress, waitingTime,
            numberOfAttempts, retryDelay, hostAndPortPairs, keyStorePath, keyStorePassword, trustStorePath,
            trustStorePassword, followRedirects, autoCloseable, staleConnectionCheckEnabled, disableCookies,
            serviceDirectoryEnabled, serviceName, autoEncodeUri);

    return metadata;

}

From source file:com.appeligo.amazon.ProgramIndexer.java

public ProgramIndexer() {
    ConfigurationService.init();//from  w ww  .j  a  v  a2s.c o m
    Configuration config = ConfigUtils.getAmazonConfig();
    indexLocation = new File(config.getString("programIndex"));
    jdbcDriver = config.getString("jdbc.driver", "com.mysql.jdbc.Driver");
    jdbcUrl = config.getString("jdbc.url");
    jdbcUsername = config.getString("jdbc.username");
    jdbcPassword = config.getString("jdbc.password");
    fetchSize = config.getInt("fetchSize", 1000);
    staleDays = config.getInt("staleDays", 30);
}

From source file:net.sf.jclal.util.mail.SenderEmail.java

/**
 *
 * @param configuration The configuration of SenderEmail.
 *
 *The XML labels supported are:// w  w  w.j a  v a2 s .c om
 *
 * <ul>
 * <li>smtp-host= ip</li>
 * <li>smtp-port= int</li>
 * <li>to= email</li>
 * <li>from= email</li>
 * <li>attach-report-file=boolean</li>
 * <li>user=String</li>
 * <li>pass=String</li>
 * </ul>
 */
@Override
public void configure(Configuration configuration) {

    String hostT = configuration.getString("smtp-host", "");
    if (hostT.isEmpty()) {
        throw new ConfigurationRuntimeException("\nThe tag <smtp-host></smtp-host> is empty.");
    }

    setHost(hostT);

    int portT = configuration.getInt("smtp-port", 21);

    setPort(portT);

    String fromT = configuration.getString("from", "");

    if (fromT.isEmpty()) {
        throw new ConfigurationRuntimeException("\nThe tag <from></from> is empty. ");
    }

    setFrom(fromT);

    // Number of defined recipients
    int numberRecipients = configuration.getList("to").size();

    if (numberRecipients == 0) {
        throw new ConfigurationRuntimeException("\nAt least one <to></to> tag must be defined. ");
    }

    // For each recipients in list
    for (int i = 0; i < numberRecipients; i++) {

        String header = "to(" + i + ")";

        // recipient 
        String recipientName = configuration.getString(header, "");

        // Add this recipient
        toRecipients.append(recipientName).append(";");
    }

    toRecipients.deleteCharAt(toRecipients.length() - 1);

    boolean attach = configuration.getBoolean("attach-report-file", false);

    setAttachReporFile(attach);

    String userT = configuration.getString("user", "");

    if (userT.isEmpty()) {
        throw new ConfigurationRuntimeException("\nThe tag <user></user> is empty. ");
    }

    setUser(userT);

    String passT = configuration.getString("pass", "");

    if (passT.isEmpty()) {
        throw new ConfigurationRuntimeException("\nThe tag <pass></pass> is empty. ");
    }

    setPass(passT);

}

From source file:net.sf.jclal.activelearning.singlelabel.querystrategy.VarianceReductionQueryStrategy.java

/**
 *
 * @param configuration Configuration for variance reduction strategy.
 *
 *The XML labels supported are:/*from  w w  w .j a  v a2s  .c om*/
 *
 * <ul>
 * <li>epsilon= double</li>
 * <li>epsilon-iteration= int</li>
 * <li>factor-regularization= double</li>
 * </ul>
 */
@Override
public void configure(Configuration configuration) {
    super.configure(configuration);

    //Set epsilon
    double currentEpsilon = configuration.getDouble("epsilon", epsilon);
    setEpsilon(currentEpsilon);

    //Set epsilon iteration
    int currentMaxEpsilonI = configuration.getInt("epsilon-iteration", maxEpsilonIteration);
    setMaxEpsilonIteration(currentMaxEpsilonI);

    //Set factor regularization
    double currentFactorRegularization = configuration.getDouble("factor-regularization", factorRegularization);
    setFactorRegularization(currentFactorRegularization);

}

From source file:com.microrisc.simply.network.udp.UDPNetworkLayerFactory.java

/**
 * @return type of UDP network layer //w  w  w  .j  ava2s  . c  om
 */
private NetworkLayerType getNetworkLayerType(Configuration configuration) throws Exception {
    String networkLayerTypeStr = configuration.getString("networkLayer.type", "");
    if (networkLayerTypeStr.equals("")) {
        throw new Exception("Network layer type not specified");
    }

    // only for "udp" layer type
    if (!networkLayerTypeStr.equals("udp")) {
        throw new SimplyException("Network layer must be of 'udp' type.");
    }

    String remoteAddress = configuration.getString("networkLayer.type.udp.remoteaddress", "");
    int remotePort = configuration.getInt("networkLayer.type.udp.remoteport", -1);

    if (remoteAddress.equals("")) {
        if (remotePort == -1) {
            return NetworkLayerType.CLIENT_MULTI;
        }
    } else {
        if (remotePort != -1) {
            return NetworkLayerType.CLIENT_SINGLE;
        }
    }

    throw new Exception("Must be specified both remote address and remote port, or" + "neither of the both");
}

From source file:edu.berkeley.sparrow.examples.HeterogeneousFrontend.java

public void run(String[] args) {
    try {/*from  w ww .j a  v a 2 s . c o m*/
        OptionParser parser = new OptionParser();
        parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
        parser.accepts("help", "print help statement");
        OptionSet options = parser.parse(args);

        if (options.has("help")) {
            parser.printHelpOn(System.out);
            System.exit(-1);
        }

        // Logger configuration: log to the console
        BasicConfigurator.configure();
        LOG.setLevel(Level.DEBUG);

        Configuration conf = new PropertiesConfiguration();

        if (options.has("c")) {
            String configFile = (String) options.valueOf("c");
            conf = new PropertiesConfiguration(configFile);
        }

        double warmupLambda = conf.getDouble("warmup_job_arrival_rate_s", DEFAULT_WARMUP_JOB_ARRIVAL_RATE_S);
        int warmupDurationS = conf.getInt("warmup_s", DEFAULT_WARMUP_S);
        int postWarmupS = conf.getInt("post_warmup_s", DEFAULT_POST_WARMUP_S);

        double lambda = conf.getDouble("job_arrival_rate_s", DEFAULT_JOB_ARRIVAL_RATE_S);
        int experimentDurationS = conf.getInt("experiment_s", DEFAULT_EXPERIMENT_S);
        LOG.debug("Using arrival rate of  " + lambda + " tasks per second and running experiment for "
                + experimentDurationS + " seconds.");
        int tasksPerJob = conf.getInt("tasks_per_job", DEFAULT_TASKS_PER_JOB);
        int numPreferredNodes = conf.getInt("num_preferred_nodes", DEFAULT_NUM_PREFERRED_NODES);
        LOG.debug("Using " + numPreferredNodes + " preferred nodes for each task.");
        int benchmarkIterations = conf.getInt("benchmark.iterations", DEFAULT_BENCHMARK_ITERATIONS);
        int benchmarkId = conf.getInt("benchmark.id", DEFAULT_TASK_BENCHMARK);

        List<String> backends = new ArrayList<String>();
        if (numPreferredNodes > 0) {
            /* Attempt to parse the list of slaves, which we'll need to (randomly) select preferred
             * nodes. */
            if (!conf.containsKey(BACKENDS)) {
                LOG.fatal("Missing configuration backend list, which is needed to randomly select "
                        + "preferred nodes (num_preferred_nodes set to " + numPreferredNodes + ")");
            }
            for (String node : conf.getStringArray(BACKENDS)) {
                backends.add(node);
            }
            if (backends.size() < numPreferredNodes) {
                LOG.fatal("Number of backends smaller than number of preferred nodes!");
            }
        }

        List<UserInfo> users = new ArrayList<UserInfo>();
        if (conf.containsKey(USERS)) {
            for (String userSpecification : conf.getStringArray(USERS)) {
                LOG.debug("Reading user specification: " + userSpecification);
                String[] parts = userSpecification.split(":");
                if (parts.length != 3) {
                    LOG.error("Unexpected user specification string: " + userSpecification + "; ignoring user");
                    continue;
                }
                users.add(new UserInfo(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[2])));
            }
        }
        if (users.size() == 0) {
            // Add a dummy user.
            users.add(new UserInfo("defaultUser", 1, 0));
        }

        SparrowFrontendClient client = new SparrowFrontendClient();
        int schedulerPort = conf.getInt("scheduler_port", SchedulerThrift.DEFAULT_SCHEDULER_THRIFT_PORT);
        client.initialize(new InetSocketAddress("localhost", schedulerPort), APPLICATION_ID, this);

        if (warmupDurationS > 0) {
            LOG.debug("Warming up for " + warmupDurationS + " seconds at arrival rate of " + warmupLambda
                    + " jobs per second");
            launchTasks(users, warmupLambda, warmupDurationS, tasksPerJob, numPreferredNodes,
                    benchmarkIterations, benchmarkId, backends, client);
            LOG.debug("Waiting for queues to drain after warmup (waiting " + postWarmupS + " seconds)");
            Thread.sleep(postWarmupS * 1000);
        }
        LOG.debug("Launching experiment for " + experimentDurationS + " seconds");
        launchTasks(users, lambda, experimentDurationS, tasksPerJob, numPreferredNodes, benchmarkIterations,
                benchmarkId, backends, client);
    } catch (Exception e) {
        LOG.error("Fatal exception", e);
    }
}