Example usage for java.util Properties containsKey

List of usage examples for java.util Properties containsKey

Introduction

In this page you can find the example usage for java.util Properties containsKey.

Prototype

@Override
    public boolean containsKey(Object key) 

Source Link

Usage

From source file:org.alfresco.reporting.processor.PropertyProcessor.java

/**
 * /*from   www. j a  v  a  2 s .  c  o  m*/
 * @param definition
 * @param nodeRef   Current nodeRef to put all related and relevant property 
 * values into the reporting database
 * @param defBacklist the Blacklist String
 * @return
 */
public Properties processPropertyDefinitions(final Properties definition, final NodeRef nodeRef) {
    if (logger.isDebugEnabled())
        logger.debug(
                "enter processPropertyDefinitions #props=" + definition.size() + " and nodeRef " + nodeRef);
    try {
        Map<QName, Serializable> map = nodeService.getProperties(nodeRef);
        if (logger.isDebugEnabled())
            logger.debug("processPropertyDefinitions: Size of map=" + map.size());
        Iterator<QName> keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = "";
            String type = "";
            try {
                QName qname = keys.next();
                //Serializable s = map.get(qname);
                if (qname != null) {
                    key = qname.toString();
                    key = replaceNameSpaces(key);

                    if (logger.isDebugEnabled())
                        logger.debug("processPropertyDefinitions: Processing key " + key);

                    if (!key.startsWith("{urn:schemas_microsoft_com:}") && !definition.containsKey(key)) {
                        type = "";
                        if (getReplacementDataType().containsKey(key)) {
                            type = getReplacementDataType().getProperty(key, "-").trim();
                        } else {
                            type = "-";
                            try {
                                type = dictionaryService.getProperty(qname).getDataType().toString().trim();
                                type = type.substring(type.indexOf("}") + 1, type.length());
                                type = getClassToColumnType().getProperty(type, "-");
                            } catch (NullPointerException npe) {
                                // ignore. cm_source and a few others have issues in their datatype??
                                logger.info("Silent drop of NullPointerException against " + key);
                            }
                            // if the key is not in the BlackList, add it to the prop object that 
                            // will update the table definition
                        }
                        if ((type != null) && !type.equals("-") && !type.equals("") && (key != null)
                                && (!key.equals(""))
                                && (!getBlacklist().toLowerCase().contains("," + key.toLowerCase() + ","))) {
                            definition.setProperty(key, type);
                            if (logger.isDebugEnabled())
                                logger.debug("processPropertyDefinitions: Adding column " + key + "=" + type);
                        } else {
                            if (logger.isDebugEnabled())
                                logger.debug("Ignoring column " + key + "=" + type);
                        }
                    } // end if containsKey
                } //end if key!=null
            } catch (Exception e) {
                logger.error("processPropertyDefinitions: Property not found! Property below...");
                logger.error("processPropertyDefinitions: type=" + type + ", key=" + key);
                e.printStackTrace();
            }
            if (logger.isDebugEnabled())
                logger.debug("processPropertyDefinitions: end while");
        } // end while
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("processPropertyDefinitions: Finally an EXCEPTION " + e.getMessage());
    }
    //logger.debug("Exit processPropertyDefinitions");
    return definition;
}

From source file:com.joseflavio.unhadegato.Concentrador.java

/**
 * {@link CopaibaGerenciador#iniciar() Iniciar}, {@link CopaibaGerenciador#atualizar(String, int, boolean, boolean, String, String, int) atualizar}
 * e/ou {@link CopaibaGerenciador#encerrar() encerrar} {@link CopaibaGerenciador}'s.
 * @param arquivo Arquivo de configurao de {@link CopaibaConexao}'s.
 *//*  w w w .j  a v  a  2 s .com*/
private static void executarCopaibas(File arquivo) {

    try {

        if (!arquivo.exists()) {
            try (InputStream is = Concentrador.class.getResourceAsStream("/copaibas.conf");
                    OutputStream os = new FileOutputStream(arquivo);) {
                IOUtils.copy(is, os);
            }
        }

        Properties props = new Properties();

        try (FileInputStream fis = new FileInputStream(arquivo)) {
            props.load(fis);
        }

        for (Object chave : props.keySet()) {

            try {

                String nome = chave.toString();

                String[] p = props.getProperty(nome).split("\",\"");

                String endereco = p[0].substring(1);
                int porta = Integer.parseInt(p[1]);
                boolean segura = p[2].equals("TLS") || p[2].equals("SSL");
                boolean ignorarCert = p[3].equals("S");
                String usuario = p[4];
                String senha = p.length >= 7 ? p[5] : p[5].substring(0, p[5].length() - 1);
                int conexoes = p.length >= 7 ? Integer.parseInt(p[6].substring(0, p[6].length() - 1)) : 5;

                CopaibaGerenciador gerenciador = gerenciadores.get(nome);

                if (gerenciador == null) {
                    log.info(Util.getMensagem("copaiba.iniciando", nome));
                    gerenciador = new CopaibaGerenciador(nome, endereco, porta, segura, ignorarCert, usuario,
                            senha, conexoes);
                    gerenciadores.put(nome, gerenciador);
                    gerenciador.iniciar();
                    log.info(Util.getMensagem("copaiba.iniciada", nome));
                } else {
                    log.info(Util.getMensagem("copaiba.verificando", nome));
                    if (gerenciador.atualizar(endereco, porta, segura, ignorarCert, usuario, senha, conexoes)) {
                        log.info(Util.getMensagem("copaiba.atualizada", nome));
                    } else {
                        log.info(Util.getMensagem("copaiba.inalterada", nome));
                    }
                }

                try (CopaibaConexao cc = new CopaibaConexao(endereco, porta, segura, ignorarCert, usuario,
                        senha)) {
                    cc.verificar();
                    log.info(Util.getMensagem("copaiba.conexao.teste.exito", nome));
                } catch (Exception e) {
                    log.info(Util.getMensagem("copaiba.conexao.teste.erro", nome, e.getMessage()));
                    log.error(e.getMessage(), e);
                }

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

        }

        Iterator<CopaibaGerenciador> it = gerenciadores.values().iterator();
        while (it.hasNext()) {
            CopaibaGerenciador gerenciador = it.next();
            String nome = gerenciador.getNome();
            if (!props.containsKey(nome)) {
                try {
                    log.info(Util.getMensagem("copaiba.encerrando", nome));
                    it.remove();
                    gerenciador.encerrar();
                    log.info(Util.getMensagem("copaiba.encerrada", nome));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

}

From source file:org.apache.jackrabbit.core.RepositoryImpl.java

/**
 * Sets the default properties of the repository.
 * <p/>//from  www . j a v a  2  s  . co  m
 * This method loads the <code>Properties</code> from the
 * <code>org/apache/jackrabbit/core/repository.properties</code> resource
 * found in the class path and (re)sets the statistics properties, if not
 * present.
 *
 * @param props the properties object to load
 *
 * @throws RepositoryException if the properties can not be loaded
 */
protected void setDefaultRepositoryProperties(Properties props) throws RepositoryException {
    InputStream in = RepositoryImpl.class.getResourceAsStream("repository.properties");
    try {
        props.load(in);
        in.close();

        // set counts
        if (!props.containsKey(STATS_NODE_COUNT_PROPERTY)) {
            props.setProperty(STATS_NODE_COUNT_PROPERTY, Long.toString(nodesCount));
        }
        if (!props.containsKey(STATS_PROP_COUNT_PROPERTY)) {
            props.setProperty(STATS_PROP_COUNT_PROPERTY, Long.toString(propsCount));
        }
    } catch (IOException e) {
        String msg = "Failed to load repository properties: " + e.toString();
        log.error(msg);
        throw new RepositoryException(msg, e);
    }
}

From source file:org.apache.solr.handler.IndexFetcher.java

/**
 * Helper method to record the last replication's details so that we can show them on the statistics page across
 * restarts./*from  w  ww. j  a  va2  s . c  o m*/
 * @throws IOException on IO error
 */
@SuppressForbidden(reason = "Need currentTimeMillis for debugging/stats")
private void logReplicationTimeAndConfFiles(Collection<Map<String, Object>> modifiedConfFiles,
        boolean successfulInstall) throws IOException {
    List<String> confFiles = new ArrayList<>();
    if (modifiedConfFiles != null && !modifiedConfFiles.isEmpty())
        for (Map<String, Object> map1 : modifiedConfFiles)
            confFiles.add((String) map1.get(NAME));

    Properties props = replicationHandler.loadReplicationProperties();
    long replicationTime = System.currentTimeMillis();
    long replicationTimeTaken = getReplicationTimeElapsed();
    Directory dir = null;
    try {
        dir = solrCore.getDirectoryFactory().get(solrCore.getDataDir(), DirContext.META_DATA,
                solrCore.getSolrConfig().indexConfig.lockType);

        int indexCount = 1, confFilesCount = 1;
        if (props.containsKey(TIMES_INDEX_REPLICATED)) {
            indexCount = Integer.valueOf(props.getProperty(TIMES_INDEX_REPLICATED)) + 1;
        }
        StringBuilder sb = readToStringBuilder(replicationTime, props.getProperty(INDEX_REPLICATED_AT_LIST));
        props.setProperty(INDEX_REPLICATED_AT_LIST, sb.toString());
        props.setProperty(INDEX_REPLICATED_AT, String.valueOf(replicationTime));
        props.setProperty(PREVIOUS_CYCLE_TIME_TAKEN, String.valueOf(replicationTimeTaken));
        props.setProperty(TIMES_INDEX_REPLICATED, String.valueOf(indexCount));
        if (modifiedConfFiles != null && !modifiedConfFiles.isEmpty()) {
            props.setProperty(CONF_FILES_REPLICATED, confFiles.toString());
            props.setProperty(CONF_FILES_REPLICATED_AT, String.valueOf(replicationTime));
            if (props.containsKey(TIMES_CONFIG_REPLICATED)) {
                confFilesCount = Integer.valueOf(props.getProperty(TIMES_CONFIG_REPLICATED)) + 1;
            }
            props.setProperty(TIMES_CONFIG_REPLICATED, String.valueOf(confFilesCount));
        }

        props.setProperty(LAST_CYCLE_BYTES_DOWNLOADED, String.valueOf(getTotalBytesDownloaded()));
        if (!successfulInstall) {
            int numFailures = 1;
            if (props.containsKey(TIMES_FAILED)) {
                numFailures = Integer.valueOf(props.getProperty(TIMES_FAILED)) + 1;
            }
            props.setProperty(TIMES_FAILED, String.valueOf(numFailures));
            props.setProperty(REPLICATION_FAILED_AT, String.valueOf(replicationTime));
            sb = readToStringBuilder(replicationTime, props.getProperty(REPLICATION_FAILED_AT_LIST));
            props.setProperty(REPLICATION_FAILED_AT_LIST, sb.toString());
        }

        String tmpFileName = REPLICATION_PROPERTIES + "." + System.nanoTime();
        final IndexOutput out = dir.createOutput(tmpFileName, DirectoryFactory.IOCONTEXT_NO_CACHE);
        Writer outFile = new OutputStreamWriter(new PropertiesOutputStream(out), StandardCharsets.UTF_8);
        try {
            props.store(outFile, "Replication details");
            dir.sync(Collections.singleton(tmpFileName));
        } finally {
            IOUtils.closeQuietly(outFile);
        }

        solrCore.getDirectoryFactory().renameWithOverwrite(dir, tmpFileName, REPLICATION_PROPERTIES);
    } catch (Exception e) {
        LOG.warn("Exception while updating statistics", e);
    } finally {
        if (dir != null) {
            solrCore.getDirectoryFactory().release(dir);
        }
    }
}

From source file:com.jaspersoft.jasperserver.war.xmla.XmlaRepositoryImpl.java

private Properties getMondrianConnectionProperties(MondrianServer server, DatabaseInfo databaseInfo,
        CatalogInfo catalogInfo, String roleName, Properties props) throws SQLException {
    //Get current session id
    String currentSessionId = getCurrentUserSessionId();
    //Generated cached key based on authorized session id, datasource, catalog name and tenant id.
    String cacheKey = currentSessionId + "_" + databaseInfo.name + "_" + catalogInfo.name + "_"
            + catalogInfo.tenantId;/*ww w. ja  v a2  s  .c o m*/

    Map<String, Object> connectProperties = new HashMap<String, Object>();
    connectProperties.putAll(databaseInfo.properties);
    connectProperties.put("DataSourceInfo", catalogInfo.connectString);

    synchronized (this.olapConnectionPropertiesCache) {
        cleanExpired(this.olapConnectionPropertiesCache);

        Properties properties;
        if (olapConnectionPropertiesCache.get(cacheKey) != null) {
            properties = olapConnectionPropertiesCache.get(cacheKey).getValue();
        } else {
            properties = xmlaContentFinder.getMondrianConnectionProperties(connectProperties, roleName);
            olapConnectionPropertiesCache.put(cacheKey, new CacheElement<Properties>(properties));
        }

        // Save the server for the duration of the call to 'getConnection'.
        final LockBox.Entry entry = JsMondrianServerRegistry.INSTANCE.getLockBox().register(server);
        properties.setProperty(RolapConnectionProperties.Instance.name(), entry.getMoniker());

        // Make sure we load the Mondrian driver into the ClassLoader.
        try {
            ClassResolver.INSTANCE.forName(MondrianOlap4jDriver.class.getName(), true);
        } catch (ClassNotFoundException e) {
            throw new OlapException("Cannot find mondrian olap4j driver.");
        }

        if (props != null && props.containsKey(XmlaHandler.JDBC_LOCALE)) {
            properties.put(XmlaHandler.JDBC_LOCALE, props.get(XmlaHandler.JDBC_LOCALE));
        }

        return properties;
    }
}

From source file:org.bultreebank.labpipe.utils.DataUtils.java

/**
 * Converts a <code>DSpin Sentence</code> object into a 
 * <code>ArrayList&lt;String&gt;</code> that can be used in constructing 
 * {@link Conll} objects.//from   www. j a v  a 2 s .  c o m
 * 
 * @param   sentence    <code>DSpin Sentence</code> object
 * @param   cm          {@link ClassMap} object
 * @param   conllMap    <code>Map</code> linking BTB tags to their CoNLL representation forms (features)
 * 
 * @return  ArrayList&lt;String&gt;
 */
public static ArrayList<String> dspinSentAsConllArray(Sentence sentence, ClassMap cm, Properties conllMap) {

    ArrayList<String> conllSentence = new ArrayList();

    List<TokenRef> tokRefs = sentence.getTokenRef();

    int id = 1;

    StringBuilder conllLine;

    Lemmas lemmas = (Lemmas) cm.get(Lemmas.class);
    Token token = null;
    Lemma lemma = null;
    Tag tagXml = null;
    String tag = null;
    Depparsing.Parse parse = null;
    Dependency dependency = null;
    HashMap tokenIndex = new HashMap();

    try {
        for (TokenRef tokRef : tokRefs) {

            conllLine = new StringBuilder();

            // Id
            conllLine.append(id);
            conllLine.append("\t");
            id++;

            // Token
            token = (Token) tokRef.getTokID();
            conllLine.append(token.getValue());
            tokenIndex.put(token, new Integer(id - 1));
            conllLine.append("\t");

            // Lemma
            if (lemmas != null) {
                lemma = (Lemma) DataUtils.getBackRef(lemmas.getLemma(), token);
                if (lemma != null && lemma.getValue().length() > 0) {
                    conllLine.append(lemma.getValue().replaceAll(" ", "_"));
                } else {
                    conllLine.append("_");
                }
            } else {
                conllLine.append("_");
            }
            conllLine.append("\t");

            if (cm.get(POStags.class) != null) {

                tagXml = (Tag) DataUtils.getBackRef(((POStags) cm.get(POStags.class)).getTag(), token);
                tag = tagXml.getValue();

                // Short tag (BTB first letter)
                if (tag.contains("punct")) {
                    conllLine.append("Punct");
                } else {
                    conllLine.append(tag.charAt(0));
                }
                conllLine.append("\t");

                // Long tag
                if (tag.contains("punct") || tag.contains("Punct")) {
                    conllLine.append("Punct");
                } else if (tag.startsWith("V")) {
                    conllLine.append(tag.substring(0, 3));
                } else if (tag.length() > 2 && tag.charAt(1) != '-') {
                    conllLine.append(tag.substring(0, 2));
                } else if (tag.length() >= 2 && tag.charAt(1) == '-') {
                    conllLine.append(tag.charAt(0));
                } else {
                    conllLine.append(tag);
                }
                conllLine.append("\t");

                // Features (rest of the tag separated with pipe signs)
                if (conllMap.containsKey(tag)) { // using the map configuration

                    conllLine.append(conllMap.getProperty(tag));

                } else { // tags not listed in the map -- failsafe

                    if (tag.length() > 2 && !tag.contains("unct")) {

                        conllLine.append(StringUtils.join(tag.substring(2).split(""), "|").substring(1));

                    } else {

                        conllLine.append("_");

                    }

                }

            } else {
                conllLine.append("_\t_\t_");
            }
            conllLine.append("\t");

            // Dependency Parsing
            if (cm.containsKey(Depparsing.class)) {

                List parseList = ((Depparsing) cm.get(Depparsing.class)).getParse();

                if (!parseList.isEmpty()) {

                    parse = (Depparsing.Parse) DataUtils.getBackRef(parseList, token);

                    if (parse != null && parse.getID().substring(3).equals(sentence.getID().substring(3))) {

                        dependency = (Dependency) DataUtils.getBackRef(parse.getDependency(), token);

                        conllLine.append(tokenIndex.get(dependency.getGovID()));
                        conllLine.append("\t");
                        conllLine.append(dependency.getFunc());
                        conllLine.append("\t");

                    }

                }

            }

            conllSentence.add(conllLine.toString());

        }
    } catch (NullPointerException ex) {
        logger.log(Level.SEVERE, "Error occurred during parsing of sentence number ".concat((id - 1) + ""), ex);
    }

    return conllSentence;

}

From source file:annis.administration.AdministrationDao.java

/**
 * Searches for textes which are empty or only contains whitespaces. If that
 * is the case the visualizer and no document visualizer are defined in the
 * corpus properties file a new file is created and stores a new config which
 * disables document browsing.//from  w  w  w  . ja v a  2s  .  c o m
 *
 *
 * @param corpusID The id of the corpus which texts are analyzed.
 */
private void analyzeTextTable(String toplevelCorpusName) {
    List<String> rawTexts = getAnnisDao().getRawText(toplevelCorpusName);

    // pattern for checking the token layer
    final Pattern WHITESPACE_MATCHER = Pattern.compile("^\\s+$");

    for (String s : rawTexts) {

        if (s != null && WHITESPACE_MATCHER.matcher(s).matches()) {
            // deactivate doc browsing if no document browser configuration is exists
            if (getAnnisDao().getDocBrowserConfiguration(toplevelCorpusName) == null) {
                // should exists anyway
                Properties corpusConf;
                try {
                    corpusConf = getAnnisDao().getCorpusConfiguration(toplevelCorpusName);
                } catch (FileNotFoundException ex) {
                    log.error("not found a corpus configuration, so skip analyzing the text table", ex);
                    return;
                }

                // disable document browsing if it is not explicit switch on by the
                // user in the corpus.properties
                boolean hasKey = corpusConf.containsKey("browse-documents");
                boolean isActive = Boolean.parseBoolean(corpusConf.getProperty("browse-documents"));

                if (!(hasKey && isActive)) {
                    log.info("disable document browser");
                    corpusConf.put("browse-documents", "false");
                    getAnnisDao().setCorpusConfiguration(toplevelCorpusName, corpusConf);
                }

                // once disabled don't search in further texts
                return;
            }
        }
    }
}

From source file:io.warp10.continuum.egress.EgressFetchHandler.java

public EgressFetchHandler(KeyStore keystore, Properties properties, DirectoryClient directoryClient,
        StoreClient storeClient) {//w w  w  . j a  v  a2s. c  o  m
    this.fetchPSK = keystore.getKey(KeyStore.SIPHASH_FETCH_PSK);
    this.fetchAES = keystore.getKey(KeyStore.AES_FETCHER);
    this.storeClient = storeClient;
    this.directoryClient = directoryClient;

    if (properties.containsKey(Configuration.EGRESS_FETCH_BATCHSIZE)) {
        FETCH_BATCHSIZE = Long.parseLong(properties.getProperty(Configuration.EGRESS_FETCH_BATCHSIZE));
    }

    if (properties.containsKey(Configuration.EGRESS_FETCHER_MAXSPLITAGE)) {
        this.maxSplitAge = Long.parseLong(properties.getProperty(Configuration.EGRESS_FETCHER_MAXSPLITAGE));
    } else {
        this.maxSplitAge = Long.MAX_VALUE;
    }
}

From source file:org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011.java

/**
 * Creates a FlinkKafkaProducer for a given topic. The sink produces its input to
 * the topic. It accepts a keyed {@link KeyedSerializationSchema} and possibly a custom {@link FlinkKafkaPartitioner}.
 *
 * <p>If a partitioner is not provided, written records will be partitioned by the attached key of each
 * record (as determined by {@link KeyedSerializationSchema#serializeKey(Object)}). If written records do not
 * have a key (i.e., {@link KeyedSerializationSchema#serializeKey(Object)} returns {@code null}), they
 * will be distributed to Kafka partitions in a round-robin fashion.
 *
 * @param defaultTopicId The default topic to write data to
 * @param serializationSchema A serializable serialization schema for turning user objects into a kafka-consumable byte[] supporting key/value messages
 * @param producerConfig Configuration properties for the KafkaProducer. 'bootstrap.servers.' is the only required argument.
 * @param customPartitioner A serializable partitioner for assigning messages to Kafka partitions.
 *                          If a partitioner is not provided, records will be partitioned by the key of each record
 *                          (determined by {@link KeyedSerializationSchema#serializeKey(Object)}). If the keys
 *                          are {@code null}, then records will be distributed to Kafka partitions in a
 *                          round-robin fashion.
 * @param semantic Defines semantic that will be used by this producer (see {@link Semantic}).
 * @param kafkaProducersPoolSize Overwrite default KafkaProducers pool size (see {@link Semantic#EXACTLY_ONCE}).
 *//*www  . j  a va 2s  .  c om*/
public FlinkKafkaProducer011(String defaultTopicId, KeyedSerializationSchema<IN> serializationSchema,
        Properties producerConfig, Optional<FlinkKafkaPartitioner<IN>> customPartitioner, Semantic semantic,
        int kafkaProducersPoolSize) {
    super(new TransactionStateSerializer(), new ContextStateSerializer());

    this.defaultTopicId = checkNotNull(defaultTopicId, "defaultTopicId is null");
    this.schema = checkNotNull(serializationSchema, "serializationSchema is null");
    this.producerConfig = checkNotNull(producerConfig, "producerConfig is null");
    this.flinkKafkaPartitioner = checkNotNull(customPartitioner, "customPartitioner is null").orElse(null);
    this.semantic = checkNotNull(semantic, "semantic is null");
    this.kafkaProducersPoolSize = kafkaProducersPoolSize;
    checkState(kafkaProducersPoolSize > 0, "kafkaProducersPoolSize must be non empty");

    ClosureCleaner.clean(this.flinkKafkaPartitioner, true);
    ClosureCleaner.ensureSerializable(serializationSchema);

    // set the producer configuration properties for kafka record key value serializers.
    if (!producerConfig.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) {
        this.producerConfig.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                ByteArraySerializer.class.getName());
    } else {
        LOG.warn("Overwriting the '{}' is not recommended", ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG);
    }

    if (!producerConfig.containsKey(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) {
        this.producerConfig.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                ByteArraySerializer.class.getName());
    } else {
        LOG.warn("Overwriting the '{}' is not recommended", ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG);
    }

    // eagerly ensure that bootstrap servers are set.
    if (!this.producerConfig.containsKey(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) {
        throw new IllegalArgumentException(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG
                + " must be supplied in the producer config properties.");
    }

    if (!producerConfig.containsKey(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG)) {
        long timeout = DEFAULT_KAFKA_TRANSACTION_TIMEOUT.toMilliseconds();
        checkState(timeout < Integer.MAX_VALUE && timeout > 0, "timeout does not fit into 32 bit integer");
        this.producerConfig.put(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG, (int) timeout);
        LOG.warn("Property [{}] not specified. Setting it to {}", ProducerConfig.TRANSACTION_TIMEOUT_CONFIG,
                DEFAULT_KAFKA_TRANSACTION_TIMEOUT);
    }

    // Enable transactionTimeoutWarnings to avoid silent data loss
    // See KAFKA-6119 (affects versions 0.11.0.0 and 0.11.0.1):
    // The KafkaProducer may not throw an exception if the transaction failed to commit
    if (semantic == Semantic.EXACTLY_ONCE) {
        final Object object = this.producerConfig.get(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG);
        final long transactionTimeout;
        if (object instanceof String && StringUtils.isNumeric((String) object)) {
            transactionTimeout = Long.parseLong((String) object);
        } else if (object instanceof Number) {
            transactionTimeout = ((Number) object).longValue();
        } else {
            throw new IllegalArgumentException(
                    ProducerConfig.TRANSACTION_TIMEOUT_CONFIG + " must be numeric, was " + object);
        }
        super.setTransactionTimeout(transactionTimeout);
        super.enableTransactionTimeoutWarnings(0.8);
    }

    this.topicPartitionsMap = new HashMap<>();
}

From source file:com.adito.agent.client.ProxyUtil.java

/**
 * Attempt to proxy settings from Firefox.
 * //from  ww w  .  j ava  2  s .  c om
 * @return firefox proxy settings
 * @throws IOException if firefox settings could not be obtained for some
 *         reason
 */
public static BrowserProxySettings lookupFirefoxProxySettings() throws IOException {

    try {

        Vector proxies = new Vector();
        Vector bypassAddr = new Vector();

        File home = new File(Utils.getHomeDirectory());
        File firefoxAppData;

        if (System.getProperty("os.name") != null && System.getProperty("os.name").startsWith("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            firefoxAppData = new File(home, "Application Data\\Mozilla\\Firefox\\profiles.ini"); //$NON-NLS-1$
        } else {
            firefoxAppData = new File(home, ".mozilla/firefox/profiles.ini"); //$NON-NLS-1$
        }

        // Look for Path elements in the profiles.ini
        BufferedReader reader = null;
        Hashtable profiles = new Hashtable();
        String line;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(firefoxAppData)));
            String currentProfileName = ""; //$NON-NLS-1$

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("[") && line.endsWith("]")) { //$NON-NLS-1$ //$NON-NLS-2$
                    currentProfileName = line.substring(1, line.length() - 1);
                    continue;
                }

                if (line.startsWith("Path=")) { //$NON-NLS-1$
                    profiles.put(currentProfileName, new File(firefoxAppData.getParent(), line.substring(5)));
                }
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        // Iterate through all the profiles and load the proxy infos from
        // the prefs.js file

        File prefsJS;
        String profileName;
        for (Enumeration e = profiles.keys(); e.hasMoreElements();) {
            profileName = (String) e.nextElement();
            prefsJS = new File((File) profiles.get(profileName), "prefs.js"); //$NON-NLS-1$
            Properties props = new Properties();
            reader = null;
            try {
                if (!prefsJS.exists()) {
                    // needed to defend against un-initialised profiles.
                    // #ifdef DEBUG
                    log.info("The file " + prefsJS.getAbsolutePath() + " does not exist."); //$NON-NLS-1$
                    // #endif
                    // now remove it from the map.
                    profiles.remove(profileName);
                    continue;
                }
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(prefsJS)));
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("user_pref(\"")) { //$NON-NLS-1$
                        int idx = line.indexOf("\"", 11); //$NON-NLS-1$
                        if (idx == -1)
                            continue;
                        String pref = line.substring(11, idx);

                        // Save this position
                        int pos = idx + 1;

                        // Look for another quote
                        idx = line.indexOf("\"", idx + 1); //$NON-NLS-1$

                        String value;
                        if (idx == -1) {
                            // No more quotes
                            idx = line.indexOf(" ", pos); //$NON-NLS-1$

                            if (idx == -1)
                                continue;

                            int idx2 = line.indexOf(")", pos); //$NON-NLS-1$

                            if (idx2 == -1)
                                continue;

                            value = line.substring(idx + 1, idx2);

                        } else {

                            // String value
                            int idx2 = line.indexOf("\"", idx + 1); //$NON-NLS-1$

                            if (idx2 == -1)
                                continue;

                            value = line.substring(idx + 1, idx2);
                        }

                        props.put(pref, value);

                    }
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
            ProxyInfo p;
            /**
             * Extract some proxies from the properites, if the proxy is
             * enabled
             */
            if ("1".equals(props.get("network.proxy.type"))) { //$NON-NLS-1$ //$NON-NLS-2$
                boolean isProfileActive = checkProfileActive(prefsJS);
                if (props.containsKey("network.proxy.ftp")) { //$NON-NLS-1$
                    p = createProxyInfo(
                            "ftp=" + props.get("network.proxy.ftp") + ":" + props.get("network.proxy.ftp_port"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                            "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.http")) { //$NON-NLS-1$
                    p = createProxyInfo(
                            "http=" + props.get("network.proxy.http") + ":" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                    + props.get("network.proxy.http_port"), //$NON-NLS-1$
                            "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.ssl")) { //$NON-NLS-1$
                    p = createProxyInfo(
                            "ssl=" + props.get("network.proxy.ssl") + ":" + props.get("network.proxy.ssl_port"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                            "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.socks")) { //$NON-NLS-1$
                    p = createProxyInfo("socks=" + props.get("network.proxy.socks") + ":" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            + props.get("network.proxy.socks_port"), "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.no_proxies_on")) { //$NON-NLS-1$

                    StringTokenizer tokens = new StringTokenizer(
                            props.getProperty("network.proxy.no_proxies_on"), ","); //$NON-NLS-1$ //$NON-NLS-2$

                    while (tokens.hasMoreTokens()) {
                        bypassAddr.addElement(((String) tokens.nextToken()).trim());
                    }

                }
            }
        }

        // need to ensure that the returned values are sorted correctly...
        BrowserProxySettings bps = new BrowserProxySettings();
        bps.setBrowser("Mozilla Firefox"); //$NON-NLS-1$
        bps.setProxiesActiveFirst(proxies);
        bps.setBypassAddr(new String[bypassAddr.size()]);
        bypassAddr.copyInto(bps.getBypassAddr());
        return bps;

    } catch (Throwable t) {
        throw new IOException("Failed to get proxy information from Firefox profiles: " + t.getMessage()); //$NON-NLS-1$
    }
}