Example usage for org.apache.commons.configuration ConfigurationException ConfigurationException

List of usage examples for org.apache.commons.configuration ConfigurationException ConfigurationException

Introduction

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

Prototype

public ConfigurationException(Throwable cause) 

Source Link

Document

Constructs a new ConfigurationException with specified nested Throwable.

Usage

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Configures all the needed components, but does not actually start the server.
 * @param config   Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy.
 * @throws Exception   Yeah, a lot can go wrong here, but at least it will be caught immediately :-)
 *///from  w  ww. j ava  2s  .  c  om
public void config(HierarchicalConfiguration config) throws Exception {
    List<HierarchicalConfiguration> lconf;
    HttpAsyncRequester executor = null;
    BasicNIOConnPool connPool = null;
    ObjectPool<ByteBuffer> byteBufferPool = null;
    LinkedHashMap<String, TargetDescriptor> mappings = null;
    ConcurrentMap<String, HttpHost> hosts = null;

    handlerRegistry = new UriHttpAsyncRequestHandlerMapper();

    // Initialize the keystore (if one was specified)
    KeyStore keystore = null;
    char[] keypass = null;
    String keystoreUri = config.getString("keystore");
    if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) {
        Path keystorePath = Utils.MakePath(keystoreUri);
        if (!Files.exists(keystorePath))
            throw new ConfigurationException("Keystore does not exist.");
        if (Files.isDirectory(keystorePath))
            throw new ConfigurationException("Keystore is not a file");
        String storepass = config.getString("storepass");
        if ((storepass != null) && "null".equals(storepass))
            storepass = null;
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) {
            keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray());
        } catch (IOException ex) {
            Logger.error("Unable to load https server keystore from " + keystoreUri);
            return;
        }
        keypass = config.getString("keypass").trim().toCharArray();
    }

    // Wire up the listening reactor
    lconf = config.configurationsAt("server");
    if ((lconf == null) || (lconf.size() != 1))
        throw new ConfigurationException("One (and only one) server configuration element is allowed.");
    else {
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667)));
        builder.setSoTimeout(config.getInt("server[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("server[@soLinger]", -1));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        builder.setSelectInterval(100);

        IOReactorConfig rconfig = builder.build();
        Logger.info("Configuring server with options: " + rconfig.toString());
        listeningReactor = new DefaultListeningIOReactor(rconfig);

        lconf = config.configurationsAt("server.listen");
        InetSocketAddress addr;
        boolean hasNonWildcardSecure = false;
        LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>();
        if ((lconf == null) || (lconf.size() == 0)) {
            addr = new InetSocketAddress("127.0.0.1", 8080);
            ListenerEndpoint ep = listeningReactor.listen(addr);
            Logger.warn("Configured " + ep.getAddress());
        } else {
            TrustManager[] trustManagers = null;
            KeyManagerFactory kmf = null;
            // Create all the specified listeners.
            for (HierarchicalConfiguration hc : lconf) {
                String addrStr = hc.getString("[@address]");
                if ((addrStr == null) || (addrStr.length() == 0))
                    addrStr = "0.0.0.0";
                String alias = hc.getString("[@alias]");
                int port = hc.getInt("[@port]", alias != null ? 443 : 80);
                addr = new InetSocketAddress(addrStr, port);
                ListenerEndpoint ep = listeningReactor.listen(addr);
                String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null;
                Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null;
                if ((alias != null) && (secure == null))
                    secure = true;
                if ((protocol != null) && (secure == null))
                    secure = true;
                if ((secure != null) && secure) {
                    if (protocol == null)
                        protocol = "TLS";
                    if (keystore == null)
                        throw new ConfigurationException(
                                "An https listening socket was requested, but no keystore was specified.");
                    if (kmf == null) {
                        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        kmf.init(keystore, keypass);
                    }
                    // Are we going to trust all clients or just specific ones?
                    if (hc.getBoolean("[@trustAny]", true))
                        trustManagers = new TrustManager[] { new X509TrustAllManager() };
                    else {
                        TrustManagerFactory instance = TrustManagerFactory
                                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        instance.init(keystore);
                        trustManagers = instance.getTrustManagers();
                    }
                    KeyManager[] keyManagers = kmf.getKeyManagers();
                    if (alias != null)
                        for (int i = 0; i < keyManagers.length; i++) {
                            if (keyManagers[i] instanceof X509ExtendedKeyManager)
                                keyManagers[i] = new PokerFaceKeyManager(alias,
                                        (X509ExtendedKeyManager) keyManagers[i]);
                        }
                    SSLContext sslCtx = SSLContext.getInstance(protocol);
                    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
                    if (addr.getAddress().isAnyLocalAddress()) {
                        // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card.
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                                .hasMoreElements();) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                    .hasMoreElements();) {
                                addr = new InetSocketAddress(enumIpAddr.nextElement(), port);
                                addrSSLContext.put(addr, sslCtx);
                            }
                        }
                    } else {
                        addrSSLContext.put(addr, sslCtx);
                        hasNonWildcardSecure = true;
                    }
                }
                Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress());
            }
        }
        // We will need an HTTP protocol processor for the incoming connections
        String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version);
        HttpProcessor inhttpproc = new ImmutableHttpProcessor(
                new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent),
                        new ResponseContent(), new ResponseConnControl() });
        HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(),
                null, handlerRegistry, null) {
            public void exception(final NHttpServerConnection conn, final Exception cause) {
                Logger.warn(cause.getMessage());
                super.exception(conn, cause);
            }
        };
        if (addrSSLContext.size() > 0) {
            final SSLContext defaultCtx = addrSSLContext.values().iterator().next();
            final Map<SocketAddress, SSLContext> sslMap;
            if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1))
                sslMap = null;
            else
                sslMap = addrSSLContext;
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler,
                    new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) {
                        protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext,
                                SSLSetupHandler sslHandler) {
                            SSLIOSession retVal;
                            SSLContext sktCtx = sslcontext;
                            if (sslMap != null) {
                                SocketAddress la = iosession.getLocalAddress();
                                if (la != null) {
                                    sktCtx = sslMap.get(la);
                                    if (sktCtx == null)
                                        sktCtx = sslcontext;
                                }
                                retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler);
                            } else
                                retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler);
                            if (sktCtx != null)
                                retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true);
                            return retVal;
                        }
                    });
        } else
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT);
    }

    // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets.
    lconf = config.configurationsAt("targets");
    if ((lconf != null) && (lconf.size() > 0)) {
        HierarchicalConfiguration conf = lconf.get(0);
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667)));
        builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("targets[@soLinger]", -1));
        builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        connectingReactor = new DefaultConnectingIOReactor(builder.build());

        final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024;
        byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() {
            @Override
            public ByteBuffer create() throws Exception {
                return ByteBuffer.allocateDirect(bufferSize);
            }

            @Override
            public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) {
                return new DefaultPooledObject<ByteBuffer>(buffer);
            }
        });

        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (keystore != null) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, keypass);
            keyManagers = kmf.getKeyManagers();
        }
        // Will the httpclient's trust any remote target, or only specific ones.
        if (conf.getBoolean("targets[@trustAny]", false))
            trustManagers = new TrustManager[] { new X509TrustAllManager() };
        else if (keystore != null) {
            TrustManagerFactory instance = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            instance.init(keystore);
            trustManagers = instance.getTrustManagers();
        }
        SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS"));
        clientSSLContext.init(keyManagers, trustManagers, new SecureRandom());

        // Setup an SSL capable connection pool for the httpclients.
        connPool = new BasicNIOConnPool(connectingReactor,
                new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT),
                conf.getInt("targets[@connectTimeout]", 0));
        connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023));
        connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023));

        // Set up HTTP protocol processor for outgoing connections
        String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version);
        HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                new RequestContent(), new RequestTargetHost(), new RequestConnControl(),
                new RequestUserAgent(userAgent), new RequestExpectContinue(true) });
        executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy());

        // Now set up all the configured targets.
        mappings = new LinkedHashMap<String, TargetDescriptor>();
        hosts = new ConcurrentHashMap<String, HttpHost>();
        String[] scheme = { null };
        String[] host = { null };
        int[] port = { 0 };
        String[] path = { null };
        int[] stripPrefixCount = { 0 };
        for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) {
            String match = targetConfig.getString("[@pattern]");
            if ((match == null) || (match.trim().length() < 1)) {
                Logger.error("Unable to configure target;  Invalid url match pattern");
                continue;
            }
            String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host,
                    port, path, stripPrefixCount);
            if (key == null) {
                Logger.error("Unable to configure target");
                continue;
            }
            HttpHost targetHost = hosts.get(key);
            if (targetHost == null) {
                targetHost = new HttpHost(host[0], port[0], scheme[0]);
                hosts.put(key, targetHost);
            }
            TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]);
            mappings.put(match, desc);
        }
        connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(),
                ConnectionConfig.DEFAULT);
    }
    // Allocate the script map which will be populated by it's own executor thread.
    if (config.containsKey("scripts.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Scripts directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'scripts' path is not a directory.");
        scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>();
        boolean watch = config.getBoolean("scripts.dynamicWatch", false);
        List<Path> jsLibs;
        Object prop = config.getProperty("scripts.library");
        if (prop != null) {
            jsLibs = new ArrayList<Path>();
            if (prop instanceof Collection<?>) {
                @SuppressWarnings("unchecked")
                Collection<Object> oprop = (Collection<Object>) prop;
                for (Object obj : oprop)
                    jsLibs.add(Utils.MakePath(obj));
            } else {
                jsLibs.add(Utils.MakePath(prop));
            }
        } else
            jsLibs = null;

        lconf = config.configurationsAt("scripts.scriptConfig");
        if (lconf != null) {
            if (lconf.size() > 1)
                throw new ConfigurationException("Only one scriptConfig element is allowed.");
            if (lconf.size() == 0)
                lconf = null;
        }

        HierarchicalConfiguration scriptConfig;
        if (lconf == null)
            scriptConfig = new HierarchicalConfiguration();
        else
            scriptConfig = lconf.get(0);
        scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString());

        configureScripts(jsLibs, scriptConfig, tmp, watch);
        if (watch)
            ScriptDirectoryWatcher = new DirectoryWatchService();
    }

    // Configure the static file directory (if any)
    Path staticFilesPath = null;
    if (config.containsKey("files.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Files directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'files' path is not a directory.");
        staticFilesPath = tmp;
        List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry");
        if (mimeEntries != null) {
            for (HierarchicalConfiguration entry : mimeEntries) {
                entry.setDelimiterParsingDisabled(true);
                String type = entry.getString("[@type]", "").trim();
                if (type.length() == 0)
                    throw new ConfigurationException("Invalid mime type entry");
                String extensions = entry.getString("[@extensions]", "").trim();
                if (extensions.length() == 0)
                    throw new ConfigurationException("Invalid mime extensions for: " + type);
                ScriptHelperImpl.AddMimeEntry(type, extensions);
            }
        }
    }

    handlerRegistry.register("/*",
            new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings,
                    scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null,
                    config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null));
}

From source file:ch.admin.suis.msghandler.config.SedexCertConfigFactory.java

/**
 * Method used to handle a private certificate given by {@link #parseFile(XMLConfiguration, String)}
 *
 * @param i          The iterator/*  w  w  w.  j  a  va  2s .  co m*/
 * @param configFile The config file
 * @return A list of certificates
 * @throws ConfigurationException A config error.
 */
private List<SedexCertConfig> handlePrivateCertificate(Iterator i, String configFile)
        throws ConfigurationException {
    List<SedexCertConfig> sedexCfgs = new ArrayList<>();
    HierarchicalConfiguration sub = (HierarchicalConfiguration) i.next();

    File p12File = determinePrivateKeyLocation(sub.getString("location"), configFile);
    if (null == p12File) {
        throw new ConfigurationException("The referenced file " + configFile
                + " contains filenames with variables!\n"
                + "(probably ${ADAPTER_HOME} of ${SEDEX_HOME})! Define a environment variable with that name."
                + "The variable must point to the directory, where the sedex adpater is installed.");
    }
    if (!p12File.exists()) {
        throw new ConfigurationException("Maybe incorrect configuration in file: " + configFile
                + ", specified p12 file not found: " + p12File.getAbsolutePath());
    }

    String password = sub.getString("password");
    Date expireDate = null;

    List optionalInfo = sub.configurationsAt(".optionalInfo");
    if (optionalInfo.size() == 1) {
        HierarchicalConfiguration optionalSub = (HierarchicalConfiguration) optionalInfo.get(0);
        String sExpiryDate = optionalSub.getString("expirydate");
        try {
            expireDate = ISO8601Utils.parse(sExpiryDate);
        } catch (IllegalArgumentException ex) {
            throw new ConfigurationException("Unable to parse date: " + sExpiryDate, ex);
        }
    }

    SedexCertConfig sedexConfig = new SedexCertConfig(p12File, password, expireDate);
    LOG.debug("Found: " + sedexConfig.toString());
    sedexCfgs.add(sedexConfig);

    return sedexCfgs;
}

From source file:jdbc.pool.CXMLManager.java

protected CPoolAttribute getPoolAttribute(String name) throws ConfigurationException {
    int iSize = xmlPoolConfig.getMaxIndex("pool[@name]");
    for (int i = 0; i <= iSize; i++) {
        if (xmlPoolConfig.getString("pool(" + i + ")[@name]").equals(name)) {
            return getPoolAttribute(i);
        }/*from ww w . j ava  2  s  . c o m*/
    }
    throw new ConfigurationException("Unable to locate pool.");
}

From source file:ch.admin.suis.msghandler.config.ClientConfigurationFactory.java

/**
 * Initialize the factory with a XML file located at the given path. This is a relative path to a location somewhere
 * in the classpath.//from  w  w  w . j  a  v a 2s  .  c  o m
 * Has to be called!
 */
@SuppressWarnings("unchecked")
public void init() throws ConfigurationException {
    // set the unlimited policy directly. Siehe https://golb.hplar.ch/p/JCE-policy-changes-in-Java-SE-8u151-and-8u152
    Security.setProperty("crypto.policy", "unlimited");

    // load the BouncyCastle provider
    Security.addProvider(new BouncyCastleProvider());

    checkSigningOutboxDirSet.clear(); // clear set...
    checkSigningProcessedDirSet.clear();

    clientConfiguration.setSedexAdapterConfiguration(createSedexAdapterConfig(xmlConfig));
    LOG.info("Sedex adapter configuration added, " + clientConfiguration.getSedexAdapterConfiguration());

    final String baseDir = createBaseDir(xmlConfig);

    clientConfiguration.setWorkingDir(createWorkingDir(xmlConfig));

    // SEDEX-175 - cleans the working dir up.

    cleanUpWorkingDir(clientConfiguration.getWorkingDir());

    // Sets the outbox limit
    long secondsControllerBeforeSendingStuff = xmlConfig.getLong("messageHandler.minimumFileAge[@waitFor]", 0);
    if (secondsControllerBeforeSendingStuff == 0) {
        LOG.warn(
                "No delayer has been set with the key messageHandler.minimumFileAge.waitFor, which means every file "
                        + "will be sent ASAP instead of waiting for a bit ! This is usually a bad idea for big files as "
                        + "they tend to be slow...");
    }

    Outbox.secondsBeforeSending = secondsControllerBeforeSendingStuff;

    //Sets the inbox limit
    long maximumInboxFiles = xmlConfig.getLong("messageHandler.maximumIncomingMessages[@accept]",
            Long.MAX_VALUE);
    if (maximumInboxFiles == 0) {
        LOG.error(
                "MessageHandler is configured to accept a maximum of 0 documents in each inbox. This is unacceptable.");
        throw new ConfigurationException("Cannot put 0 as a throttle for inboxes.");
    }
    Inbox.incomingMessageLimit = maximumInboxFiles;

    // **************** receiver-specific settings
    ReceiverConfiguration receiverConfiguration = setupReceiver();

    // **************** checker-specific settings
    StatusCheckerConfiguration statusCheckerConfiguration = setupChecker();

    final String defaultSenderCronValue = xmlConfig.getString("messageHandler.defaultOutboxCheck[@cron]");
    if (StringUtils.isBlank(defaultSenderCronValue)) {
        throw new ConfigurationException("Missing attribute: messageHandler.defaultOutboxCheck[@cron]");
    }
    // create default sender configuration - with the default cron
    final SenderConfiguration defaultSenderConfiguration = new SenderConfiguration(defaultSenderCronValue);

    setupNativeApps(defaultSenderConfiguration, baseDir, receiverConfiguration);

    if (!defaultSenderConfiguration.getOutboxes().isEmpty()) {
        // if the default config contains at least one outbox, add it to the client config
        clientConfiguration.addSenderConfiguration(defaultSenderConfiguration);
        // MANTIS 5023
        LOG.info("sender added, " + defaultSenderConfiguration);
    }
    // Setting up transparent apps...
    setupTransparentApps(defaultSenderCronValue, baseDir, receiverConfiguration, statusCheckerConfiguration);
    // Launching jetty...
    setupHttpServer();
}

From source file:jdbc.pool.CPropertyManager.java

public synchronized boolean update(CPoolAttribute attribute) throws ConfigurationException {
    StringTokenizer tokenizer = new StringTokenizer(properties_.getProperty("pools"), ";");
    boolean bPoolConfigurationFound = false;
    while (tokenizer.hasMoreTokens()) {
        if (tokenizer.nextToken().equals(attribute.getPoolName())) {
            bPoolConfigurationFound = true;
            break;
        }//from w w w . jav  a  2s .  c o m
    }
    if (!bPoolConfigurationFound) {
        throw new ConfigurationException("Pool Configuration does not exists. Could not update.");
    }
    String strPoolName = attribute.getPoolName();
    properties_.setProperty(strPoolName + ".driver", attribute.getDriver());
    properties_.setProperty(strPoolName + ".vendor", attribute.getVendor());
    properties_.setProperty(strPoolName + ".url", attribute.getURL());
    properties_.setProperty(strPoolName + ".user", attribute.getUser());
    properties_.setProperty(strPoolName + ".password", attribute.getPassword());
    properties_.setProperty(strPoolName + ".initial-connections", attribute.getInitialPoolSize() + "");
    properties_.setProperty(strPoolName + ".capacity-increament", attribute.getCapacityIncreament() + "");
    properties_.setProperty(strPoolName + ".maximum-capacity", attribute.getMaximumCapacity() + "");
    properties_.setProperty(strPoolName + ".inactive-time-out", attribute.getConnectionIdleTimeout() + "");
    properties_.setProperty(strPoolName + ".shrink-pool-interval", attribute.getShrinkPoolInterval() + "");
    properties_.setProperty(strPoolName + ".critical-operation-time-limit",
            attribute.getCriticalOperationTimeLimit() + "");
    properties_.setProperty(strPoolName + ".max-usage-per-jdbc-connection",
            attribute.getMaxUsagePerJDBCConnection() + "");
    properties_.setProperty(strPoolName + ".in-use-wait-time", attribute.getInUseWaitTime() + "");
    properties_.setProperty(strPoolName + ".load-on-startup", attribute.isLoadOnStartup() + "");
    properties_.setProperty(strPoolName + ".pool-algorithm", attribute.getPoolAlgorithm());
    properties_.setProperty(strPoolName + ".inmemory-statistics-history-size",
            attribute.getStatisticalHistoryRecordCount() + "");
    properties_.setProperty(strPoolName + ".sql-query", attribute.getSqlQuery() + "");

    return true;
}

From source file:com.liferay.ide.core.properties.PortalPropertiesConfigurationLayout.java

public void save(Writer out) throws ConfigurationException {
    try {/*ww  w  . j  a  v a2  s  .  co m*/
        char delimiter = getConfiguration().isDelimiterParsingDisabled() ? 0
                : getConfiguration().getListDelimiter();

        PluginPropertiesWriter writer = new PluginPropertiesWriter(out, delimiter);

        if (getHeaderComment() != null) {
            writer.writeln(getCanonicalHeaderComment(true));
            writer.writeln(null);
        }

        List<Object> keyList = Arrays.asList(getKeys().toArray());

        Collections.sort(keyList, new Comparator<Object>() {

            public int compare(Object o1, Object o2) {
                int index1 = Integer.MAX_VALUE;
                int index2 = Integer.MAX_VALUE;

                for (int i = 0; i < sortedKeys.length; i++) {
                    if (sortedKeys[i].equals(o1)) {
                        index1 = i;
                    }

                    if (sortedKeys[i].equals(o2)) {
                        index2 = i;
                    }
                }

                if (index1 < index2) {
                    return -1;
                } else if (index1 > index2) {
                    return 1;
                }

                return 0;
            }

        });

        for (Iterator it = keyList.iterator(); it.hasNext();) {
            String key = (String) it.next();

            if (getConfiguration().containsKey(key)) {

                // Output blank lines before property
                for (int i = 0; i < getBlancLinesBefore(key); i++) {
                    writer.writeln(null);
                }

                // Output the comment
                if (getComment(key) != null) {
                    writer.writeln(getCanonicalComment(key, true));
                }

                // Output the property and its value
                boolean singleLine = (isForceSingleLine() || isSingleLine(key))
                        && !getConfiguration().isDelimiterParsingDisabled();

                boolean wrappedProperty = isWrappedProperty(key);

                writer.writeProperty(key, getConfiguration().getProperty(key), singleLine, wrappedProperty);
            }
        }

        writer.flush();
        writer.close();
    } catch (IOException ioex) {
        throw new ConfigurationException(ioex);
    }
}

From source file:it.unimi.di.big.mg4j.document.PropertyBasedDocumentFactory.java

/** This method checks that the array of values contains just one element, and returns the element.
 * //from w  w  w .j a v  a  2  s.com
 * @param key the property name (used to build the exception message).
 * @param values the array of values.
 * @return the only value (if the array contains exactly one element).
 * @throws ConfigurationException iff <var>values</var> does not contain a single element.
 */
protected static String ensureJustOne(final String key, final String[] values) throws ConfigurationException {
    if (values.length != 1)
        throw new ConfigurationException("Property " + key + " should have just one value");
    return values[0];
}

From source file:it.unimi.di.big.mg4j.document.PropertyBasedDocumentFactory.java

/** Parses a property with given key and value, adding it to the given map. 
 *
 * <p>Currently this implementation just parses the {@link MetadataKeys#LOCALE} property.
 * <P>Subclasses should do their own parsing, returing true in case of success and
 * returning <code>super.parseProperty()</code> otherwise. 
 *  /*from   w  w w . j ava  2s.com*/
 * @param key the property key.
 * @param valuesUnused the property value; this is an array, because properties may have a list of comma-separated values.
 * @param metadataUnused the metadata map.
 * @return true if the property was parsed correctly, false if it was ignored.
 *
 */
protected boolean parseProperty(final String key, final String[] valuesUnused,
        final Reference2ObjectMap<Enum<?>, Object> metadataUnused) throws ConfigurationException {
    if (sameKey(MetadataKeys.LOCALE, key))
        throw new ConfigurationException("Locales are currently unsupported");
    return false;
}

From source file:edu.hawaii.soest.pacioos.text.SimpleTextSource.java

/**
 * Constructor: create an instance of the simple SimpleTextSource
 * @param xmlConfig //w  w  w  .ja v a2  s. com
 */
public SimpleTextSource(XMLConfiguration xmlConfig) throws ConfigurationException {

    this.xmlConfig = xmlConfig;
    // Pull the general configuration from the properties file
    Configuration config = new PropertiesConfiguration("textsource.properties");
    this.archiveMode = config.getString("textsource.archive_mode");
    this.rbnbChannelName = config.getString("textsource.rbnb_channel");
    this.serverName = config.getString("textsource.server_name ");
    this.delimiter = config.getString("textsource.delimiter");
    this.pollInterval = config.getInt("textsource.poll_interval");
    this.retryInterval = config.getInt("textsource.retry_interval");
    this.defaultDateFormat = new SimpleDateFormat(config.getString("textsource.default_date_format"));

    // parse the record delimiter from the config file
    // set the XML configuration in the simple text source for later use
    this.setConfiguration(xmlConfig);

    // set the common configuration fields
    String connectionType = this.xmlConfig.getString("connectionType");
    this.setConnectionType(connectionType);
    String channelName = xmlConfig.getString("channelName");
    this.setChannelName(channelName);
    String identifier = xmlConfig.getString("identifier");
    this.setIdentifier(identifier);
    String rbnbName = xmlConfig.getString("rbnbName");
    this.setRBNBClientName(rbnbName);
    String rbnbServer = xmlConfig.getString("rbnbServer");
    this.setServerName(rbnbServer);
    int rbnbPort = xmlConfig.getInt("rbnbPort");
    this.setServerPort(rbnbPort);
    int archiveMemory = xmlConfig.getInt("archiveMemory");
    this.setCacheSize(archiveMemory);
    int archiveSize = xmlConfig.getInt("archiveSize");
    this.setArchiveSize(archiveSize);

    // set the default channel information 
    Object channels = xmlConfig.getList("channels.channel.name");
    int totalChannels = 1;
    if (channels instanceof Collection) {
        totalChannels = ((Collection<?>) channels).size();

    }
    // find the default channel with the ASCII data string
    for (int i = 0; i < totalChannels; i++) {
        boolean isDefaultChannel = xmlConfig.getBoolean("channels.channel(" + i + ")[@default]");
        if (isDefaultChannel) {
            String name = xmlConfig.getString("channels.channel(" + i + ").name");
            this.setChannelName(name);
            String dataPattern = xmlConfig.getString("channels.channel(" + i + ").dataPattern");
            this.setPattern(dataPattern);
            String fieldDelimiter = xmlConfig.getString("channels.channel(" + i + ").fieldDelimiter");
            // handle hex-encoded field delimiters
            if (fieldDelimiter.startsWith("0x") || fieldDelimiter.startsWith("\\x")) {

                Byte delimBytes = Byte.parseByte(fieldDelimiter.substring(2), 16);
                byte[] delimAsByteArray = new byte[] { delimBytes.byteValue() };
                String delim = null;
                try {
                    delim = new String(delimAsByteArray, 0, delimAsByteArray.length, "ASCII");

                } catch (UnsupportedEncodingException e) {
                    throw new ConfigurationException("There was an error parsing the field delimiter."
                            + " The message was: " + e.getMessage());
                }
                this.setDelimiter(delim);

            } else {
                this.setDelimiter(fieldDelimiter);

            }
            String[] recordDelimiters = xmlConfig
                    .getStringArray("channels.channel(" + i + ").recordDelimiters");
            this.setRecordDelimiters(recordDelimiters);
            // set the date formats list
            List<String> dateFormats = (List<String>) xmlConfig
                    .getList("channels.channel(" + i + ").dateFormats.dateFormat");
            if (dateFormats.size() != 0) {
                for (String dateFormat : dateFormats) {

                    // validate the date format string
                    try {
                        SimpleDateFormat format = new SimpleDateFormat(dateFormat);

                    } catch (IllegalFormatException ife) {
                        String msg = "There was an error parsing the date format " + dateFormat
                                + ". The message was: " + ife.getMessage();
                        if (log.isDebugEnabled()) {
                            ife.printStackTrace();
                        }
                        throw new ConfigurationException(msg);
                    }
                }
                setDateFormats(dateFormats);
            } else {
                log.warn("No date formats have been configured for this instrument.");
            }

            // set the date fields list
            List<String> dateFieldList = xmlConfig.getList("channels.channel(" + i + ").dateFields.dateField");
            List<Integer> dateFields = new ArrayList<Integer>();
            if (dateFieldList.size() != 0) {
                for (String dateField : dateFieldList) {
                    try {
                        Integer newDateField = new Integer(dateField);
                        dateFields.add(newDateField);
                    } catch (NumberFormatException e) {
                        String msg = "There was an error parsing the dateFields. The message was: "
                                + e.getMessage();
                        throw new ConfigurationException(msg);
                    }
                }
                setDateFields(dateFields);

            } else {
                log.warn("No date fields have been configured for this instrument.");
            }
            String timeZone = xmlConfig.getString("channels.channel(" + i + ").timeZone");
            this.setTimezone(timeZone);
            break;
        }

    }

    // Check the record delimiters length and set the first and optionally second delim characters
    if (this.recordDelimiters.length == 1) {
        this.firstDelimiterByte = (byte) Integer.decode(this.recordDelimiters[0]).byteValue();
    } else if (this.recordDelimiters.length == 2) {
        this.firstDelimiterByte = (byte) Integer.decode(this.recordDelimiters[0]).byteValue();
        this.secondDelimiterByte = (byte) Integer.decode(this.recordDelimiters[1]).byteValue();

    } else {
        throw new ConfigurationException("The recordDelimiter must be one or two characters, "
                + "separated by a pipe symbol (|) if there is more than one delimiter character.");
    }
    byte[] delimiters = new byte[] {};

}

From source file:com.liferay.ide.portlet.core.PluginPropertiesConfigurationLayout.java

public void save(Writer out) throws ConfigurationException {
    try {//from   w w  w  . j  a  va2 s.co  m
        char delimiter = getConfiguration().isDelimiterParsingDisabled() ? 0
                : getConfiguration().getListDelimiter();

        PluginPropertiesWriter writer = new PluginPropertiesWriter(out, delimiter);

        if (getHeaderComment() != null) {
            writer.writeln(getCanonicalHeaderComment(true));
            writer.writeln(null);
        }

        List<Object> keyList = Arrays.asList(getKeys().toArray());

        Collections.sort(keyList, new Comparator<Object>() {
            public int compare(Object o1, Object o2) {
                int index1 = Integer.MAX_VALUE;
                int index2 = Integer.MAX_VALUE;

                for (int i = 0; i < sortedKeys.length; i++) {
                    if (sortedKeys[i].equals(o1)) {
                        index1 = i;
                    }

                    if (sortedKeys[i].equals(o2)) {
                        index2 = i;
                    }
                }

                if (index1 < index2) {
                    return -1;
                } else if (index1 > index2) {
                    return 1;
                }

                return 0;
            }

        });

        for (Iterator it = keyList.iterator(); it.hasNext();) {
            String key = (String) it.next();

            if (getConfiguration().containsKey(key)) {

                // Output blank lines before property
                for (int i = 0; i < getBlancLinesBefore(key); i++) {
                    writer.writeln(null);
                }

                // Output the comment
                if (getComment(key) != null) {
                    writer.writeln(getCanonicalComment(key, true));
                }

                // Output the property and its value
                boolean singleLine = (isForceSingleLine() || isSingleLine(key))
                        && !getConfiguration().isDelimiterParsingDisabled();

                boolean wrappedProperty = isWrappedProperty(key);

                writer.writeProperty(key, getConfiguration().getProperty(key), singleLine, wrappedProperty);
            }
        }

        writer.flush();
        writer.close();
    } catch (IOException ioex) {
        throw new ConfigurationException(ioex);
    }
}