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

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

Introduction

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

Prototype

Integer getInteger(String key, Integer defaultValue);

Source Link

Document

Get an Integer associated with the given configuration key.

Usage

From source file:org.forumj.dbextreme.db.dao.FJDao.java

public static Connection getConnection() throws SQLException, ConfigurationException {
    if (dataSource == null) {
        synchronized (FJDao.class) {
            Configuration config = FJConfiguration.getConfig();
            if (dataSource == null) {
                Integer maxActive = config.getInteger("dbcp.maxActive", 10);
                ObjectPool connectionPool = new GenericObjectPool(null, maxActive);
                String connectURI = config.getString("jdbc.url");
                String userName = config.getString("jdbc.user.name");
                String userPassword = config.getString("jdbc.user.password");
                String driver = config.getString("jdbc.driver");
                String validationQuery = config.getString("dbcp.validationQuery");
                if (driver != null) {
                    try {
                        Class.forName(driver);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }/*  w  ww.ja v  a 2  s  .co  m*/
                }
                ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, userName,
                        userPassword);
                new PoolableConnectionFactory(connectionFactory, connectionPool, null, validationQuery, false,
                        true);
                dataSource = new PoolingDataSource(connectionPool);
            }
        }
    }
    return dataSource.getConnection();
}

From source file:org.lable.oss.dynamicconfig.core.commonsconfiguration.ConcurrentConfigurationTest.java

@Test
public void testMethodWrappers() {
    CombinedConfiguration mockConfiguration = mock(CombinedConfiguration.class);
    Configuration concurrentConfiguration = new ConcurrentConfiguration(mockConfiguration, null);

    concurrentConfiguration.subset("subset");
    concurrentConfiguration.isEmpty();//from  ww w  .j  a  va 2 s  . c o  m
    concurrentConfiguration.containsKey("key");
    concurrentConfiguration.getProperty("getprop");
    concurrentConfiguration.getKeys("getkeys");
    concurrentConfiguration.getKeys();
    concurrentConfiguration.getProperties("getprops");
    concurrentConfiguration.getBoolean("getboolean1");
    concurrentConfiguration.getBoolean("getboolean2", true);
    concurrentConfiguration.getBoolean("getboolean3", Boolean.FALSE);
    concurrentConfiguration.getByte("getbyte1");
    concurrentConfiguration.getByte("getbyte2", (byte) 0);
    concurrentConfiguration.getByte("getbyte3", Byte.valueOf((byte) 0));
    concurrentConfiguration.getDouble("getdouble1");
    concurrentConfiguration.getDouble("getdouble2", 0.2);
    concurrentConfiguration.getDouble("getdouble3", Double.valueOf(0.2));
    concurrentConfiguration.getFloat("getfloat1");
    concurrentConfiguration.getFloat("getfloat2", 0f);
    concurrentConfiguration.getFloat("getfloat3", Float.valueOf(0f));
    concurrentConfiguration.getInt("getint1");
    concurrentConfiguration.getInt("getint2", 0);
    concurrentConfiguration.getInteger("getint3", 0);
    concurrentConfiguration.getLong("getlong1");
    concurrentConfiguration.getLong("getlong2", 0L);
    concurrentConfiguration.getLong("getlong3", Long.valueOf(0L));
    concurrentConfiguration.getShort("getshort1");
    concurrentConfiguration.getShort("getshort2", (short) 0);
    concurrentConfiguration.getShort("getshort3", Short.valueOf((short) 0));
    concurrentConfiguration.getBigDecimal("getbigd1");
    concurrentConfiguration.getBigDecimal("getbigd2", BigDecimal.valueOf(0.4));
    concurrentConfiguration.getBigInteger("getbigi1");
    concurrentConfiguration.getBigInteger("getbigi2", BigInteger.valueOf(2L));
    concurrentConfiguration.getString("getstring1");
    concurrentConfiguration.getString("getstring2", "def");
    concurrentConfiguration.getStringArray("stringarray");
    concurrentConfiguration.getList("getlist1");
    concurrentConfiguration.getList("getlist2", Arrays.asList("a", "b"));

    verify(mockConfiguration, times(1)).subset("subset");
    verify(mockConfiguration, times(1)).isEmpty();
    verify(mockConfiguration, times(1)).containsKey("key");
    verify(mockConfiguration, times(1)).getProperty("getprop");
    verify(mockConfiguration, times(1)).getKeys("getkeys");
    verify(mockConfiguration, times(1)).getKeys();
    verify(mockConfiguration, times(1)).getProperties("getprops");
    verify(mockConfiguration, times(1)).getBoolean("getboolean1");
    verify(mockConfiguration, times(1)).getBoolean("getboolean2", true);
    verify(mockConfiguration, times(1)).getBoolean("getboolean3", Boolean.FALSE);
    verify(mockConfiguration, times(1)).getByte("getbyte1");
    verify(mockConfiguration, times(1)).getByte("getbyte2", (byte) 0);
    verify(mockConfiguration, times(1)).getByte("getbyte3", Byte.valueOf((byte) 0));
    verify(mockConfiguration, times(1)).getDouble("getdouble1");
    verify(mockConfiguration, times(1)).getDouble("getdouble2", 0.2);
    verify(mockConfiguration, times(1)).getDouble("getdouble3", Double.valueOf(0.2));
    verify(mockConfiguration, times(1)).getFloat("getfloat1");
    verify(mockConfiguration, times(1)).getFloat("getfloat2", 0f);
    verify(mockConfiguration, times(1)).getFloat("getfloat3", Float.valueOf(0f));
    verify(mockConfiguration, times(1)).getInt("getint1");
    verify(mockConfiguration, times(1)).getInt("getint2", 0);
    verify(mockConfiguration, times(1)).getInteger("getint3", Integer.valueOf(0));
    verify(mockConfiguration, times(1)).getLong("getlong1");
    verify(mockConfiguration, times(1)).getLong("getlong2", 0L);
    verify(mockConfiguration, times(1)).getLong("getlong3", Long.valueOf(0L));
    verify(mockConfiguration, times(1)).getShort("getshort1");
    verify(mockConfiguration, times(1)).getShort("getshort2", (short) 0);
    verify(mockConfiguration, times(1)).getShort("getshort3", Short.valueOf((short) 0));
    verify(mockConfiguration, times(1)).getBigDecimal("getbigd1");
    verify(mockConfiguration, times(1)).getBigDecimal("getbigd2", BigDecimal.valueOf(0.4));
    verify(mockConfiguration, times(1)).getBigInteger("getbigi1");
    verify(mockConfiguration, times(1)).getBigInteger("getbigi2", BigInteger.valueOf(2L));
    verify(mockConfiguration, times(1)).getString("getstring1");
    verify(mockConfiguration, times(1)).getString("getstring2", "def");
    verify(mockConfiguration, times(1)).getStringArray("stringarray");
    verify(mockConfiguration, times(1)).getList("getlist1");
    verify(mockConfiguration, times(1)).getList("getlist2", Arrays.asList("a", "b"));
}

From source file:org.loggo.server.Server.java

void initialize(HierarchicalINIConfiguration config)
        throws ConfigurationException, AccumuloException, AccumuloSecurityException {
    Configuration kafkaConsumerSection = config.getSection("KafkaConsumer");
    Configuration serverSection = config.getSection("server");
    Configuration accumuloSection = config.getSection("accumulo");
    Configuration batchSection = config.getSection("batchwriter");
    Configuration kafkaSection = config.getSection("kafka");
    ClientConfiguration clientConfig = new ClientConfiguration(accumuloSection);

    // connect to accumulo, check on the table
    String username = batchSection.getString("user", Defaults.USER);
    String password = batchSection.getString("password", Defaults.PASSWORD);
    String table = batchSection.getString("table", Defaults.TABLE);
    Instance instance = new ZooKeeperInstance(clientConfig);
    Connector connector = instance.getConnector(username, new PasswordToken(password.getBytes()));
    if (!connector.tableOperations().exists(table)) {
        createTable(connector, table);/*from w w w.  ja va  2  s .c om*/
    }
    createTopic(kafkaConsumerSection.getString("zookeeper.connect"), kafkaSection);

    LinkedBlockingDeque<LogEntry> queue = new LinkedBlockingDeque<LogEntry>(
            config.getInt("queue.size", Defaults.QUEUE_SIZE));
    this.writer = new Writer(queue, clientConfig, batchSection);

    ServerBootstrap b = new ServerBootstrap();
    // @formatter:off

    // tcp
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new LoggerReaderInitializer(queue));

    // udp
    Bootstrap bb = new Bootstrap();
    bb.group(dgramGroup).channel(NioDatagramChannel.class).handler(new DgramHandler(queue));

    // @formatter:on
    String host = serverSection.getString("host", Defaults.HOST);
    serverSection.setProperty("host", host);
    if (host.equals(Defaults.HOST)) {
        try {
            serverSection.setProperty("host", InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException ex) {
            throw new RuntimeException("Unable to determine local hostname: " + ex.toString());
        }
    }
    try {
        int tcpPort = serverSection.getInteger("tcp.port", Defaults.PORT);
        channel = b.bind(host, tcpPort).sync().channel();
        tcpPort = ((InetSocketAddress) channel.localAddress()).getPort();
        serverSection.setProperty("tcp.port", tcpPort);

        int udpPort = serverSection.getInteger("udp.port", Defaults.PORT);
        Channel channel2 = bb.bind(host, udpPort).sync().channel();
        udpPort = ((InetSocketAddress) channel2.localAddress()).getPort();
        serverSection.setProperty("udp.port", udpPort);

        registerInZookeeper(serverSection);
    } catch (IOException | KeeperException | InterruptedException ex) {
        throw new RuntimeException(ex);
    }
    String zookeeperConnect = kafkaConsumerSection.getString("zookeeper.connect");
    if (zookeeperConnect != null) {
        kafkaConsumer = new KafkaConsumer();
        kafkaConsumer.initialize(config, queue);
        kafkaConsumer.start();
    }
}

From source file:org.restcomm.connect.http.filters.FileCacheServlet.java

/**
 * Process the actual request.// w w  w . ja va 2  s .  c om
 *
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not
 * (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException {
    // Validate the requested file ------------------------------------------------------------

    // Get requested file by path info.
    String requestedFile = request.getPathInfo();
    if (logger.isDebugEnabled()) {
        logger.debug("Requested path:" + requestedFile);
    }

    // Check if file is actually supplied to the request URL.
    if (requestedFile == null) {
        logger.debug("No file requested, return 404.");
        // Do your thing if the file is not supplied to the request URL.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    Configuration rootConfiguration = (Configuration) request.getServletContext()
            .getAttribute(Configuration.class.getName());
    Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings");

    String basePath = runtimeConfiguration.getString("cache-path");
    int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE);
    long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME);

    // URL-decode the file name (might contain spaces and on) and prepare file object.
    String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8");
    File file = new File(basePath, fDecodedPath);

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        logger.debug("Requested file not found, return 404.");
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + expireTime;

    // Validate request headers for caching ---------------------------------------------------
    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        logger.debug("IfNoneMatch/Etag not matching, return 304.");
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        logger.debug("IfModifiedSince not matching, return 304.");
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        return;
    }

    // Validate request headers for resume ----------------------------------------------------
    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        logger.debug("ifMatch not matching, return 412.");
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        logger.debug("ifUnmodifiedSince not matching, return 412.");
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Prepare and initialize response --------------------------------------------------------
    // Get content type by file name and content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, expand content type with the one and right character encoding.
    if (contentType.startsWith("text")) {
        contentType += ";charset=UTF-8";
    } // Else, expect for images, determine content disposition. If content type is supported by
      // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(bufferSize);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client ------------------------------------------------
    // Prepare streams.
    FileInputStream input = null;
    OutputStream output = null;

    if (content) {
        logger.debug("Content requested,streaming.");
        // Open streams.
        input = new FileInputStream(file);
        output = response.getOutputStream();
        long streamed = stream(input, output, bufferSize);
        if (logger.isDebugEnabled()) {
            logger.debug("Bytes streamed:" + streamed);
        }
    }

}

From source file:org.seedstack.seed.ws.internal.WSPlugin.java

private EndpointDefinition createEndpointDefinition(String endpoint, Configuration endpointConfiguration) {
    // Implementation class
    String implementation = endpointConfiguration.getString("implementation");
    if (implementation == null || implementation.isEmpty()) {
        throw SeedException.createNew(WSErrorCode.IMPLEMENTATION_CLASS_MISSING).put(ENDPOINT_NAME_ATTRIBUTE,
                endpoint);//  w ww  .  j a v a2 s  .c om
    }

    Class<?> implementationClass;
    try {
        implementationClass = Class.forName(implementation);
    } catch (ClassNotFoundException e) {
        throw SeedException.wrap(e, WSErrorCode.UNABLE_TO_LOAD_IMPLEMENTATION_CLASS)
                .put(ENDPOINT_NAME_ATTRIBUTE, endpoint).put(IMPLEMENTATION_CLASS_ATTRIBUTE, implementation);
    }

    // External metadata
    MetadataReader metadataReader = null;
    String externalMetadata = endpointConfiguration.getString("external-metadata");
    if (externalMetadata != null) {
        metadataReader = ExternalMetadataFeature.builder().addResources(externalMetadata).build()
                .getMetadataReader(SeedReflectionUtils.findMostCompleteClassLoader(implementationClass), false);
    }

    EndpointFactory.verifyImplementorClass(implementationClass, metadataReader);

    // Service name
    String serviceName = endpointConfiguration.getString("service-name");
    QName serviceQName;
    if (serviceName == null || serviceName.isEmpty()) {
        WebService annotation = implementationClass.getAnnotation(WebService.class);
        if (annotation != null && !annotation.targetNamespace().isEmpty()
                && !annotation.serviceName().isEmpty()) {
            serviceQName = new QName(annotation.targetNamespace(), annotation.serviceName());
        } else {
            serviceQName = EndpointFactory.getDefaultServiceName(implementationClass, metadataReader);
        }
    } else {
        serviceQName = QName.valueOf(serviceName);
    }

    // Service port
    String portName = endpointConfiguration.getString("port-name");
    QName portQName;
    if (portName == null || portName.isEmpty()) {
        WebService annotation = implementationClass.getAnnotation(WebService.class);
        if (annotation != null && !annotation.targetNamespace().isEmpty() && !annotation.portName().isEmpty()) {
            portQName = new QName(annotation.targetNamespace(), annotation.portName());
        } else {
            portQName = EndpointFactory.getDefaultPortName(serviceQName, implementationClass, metadataReader);
        }
    } else {
        portQName = QName.valueOf(portName);
    }

    // Binding
    String binding = endpointConfiguration.getString("binding");
    if (binding != null) {
        binding = getBindingIdForToken(binding);
    }

    WSBinding wsBinding = createBinding(binding, implementationClass,
            endpointConfiguration.getBoolean("enable-mtom", null),
            endpointConfiguration.getInteger("mtom-treshold", null),
            endpointConfiguration.getString("data-binding-mode", null));

    // WSDL
    String wsdlPath = endpointConfiguration.getString("wsdl",
            EndpointFactory.getWsdlLocation(implementationClass, metadataReader));
    if (wsdlPath == null || wsdlPath.isEmpty()) {
        throw SeedException.createNew(WSErrorCode.WSDL_LOCATION_MISSING).put(ENDPOINT_NAME_ATTRIBUTE, endpoint)
                .put(IMPLEMENTATION_CLASS_ATTRIBUTE, implementation);
    }

    URL wsdlURL;
    try {
        wsdlURL = resourceLoader.getResource(wsdlPath);
    } catch (MalformedURLException e) {
        throw SeedException.wrap(e, WSErrorCode.UNABLE_TO_FIND_WSDL).put(ENDPOINT_NAME_ATTRIBUTE, endpoint)
                .put(WSDL_LOCATION_ATTRIBUTE, wsdlPath);
    }

    if (wsdlURL == null) {
        throw SeedException.createNew(WSErrorCode.UNABLE_TO_FIND_WSDL).put(ENDPOINT_NAME_ATTRIBUTE, endpoint)
                .put(WSDL_LOCATION_ATTRIBUTE, wsdlPath);
    }

    SDDocumentSource primaryWSDL = docs.get(wsdlURL.toExternalForm());
    assert primaryWSDL != null;

    // Entity resolver
    EntityResolver entityResolver;
    try {
        entityResolver = XmlUtil.createEntityResolver(resourceLoader.getCatalogFile());
    } catch (MalformedURLException e) {
        LOGGER.warn("Unable to create entity resolver", e);
        entityResolver = XmlUtil.createEntityResolver(null);
    }

    return new EndpointDefinition(implementationClass, true, serviceQName, portQName, wsBinding, primaryWSDL,
            entityResolver, false, endpointConfiguration.getString("url"), endpointConfiguration);
}

From source file:org.sonar.api.utils.ServerHttpClient.java

public ServerHttpClient(Configuration configuration) {
    this(configuration.getString("sonar.host.url", "http://localhost:9000"),
            configuration.getInteger("sonar.host.connectTimeoutMs", CONNECT_TIMEOUT_MILLISECONDS),
            configuration.getInteger("sonar.host.readTimeoutMs", READ_TIMEOUT_MILLISECONDS));

}