Example usage for java.util Properties setProperty

List of usage examples for java.util Properties setProperty

Introduction

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

Prototype

public synchronized Object setProperty(String key, String value) 

Source Link

Document

Calls the Hashtable method put .

Usage

From source file:com.streamsets.datacollector.main.RuntimeInfo.java

/**
 * Store configuration from control hub in persistent manner inside data directory. This configuration will be
 * loaded on data collector start and will override any configuration from sdc.properties.
 *
 * This method call is able to remove existing properties if the value is "null". Please note that the removal will
 * only happen from the 'override' file. This method does not have the capability to remove configuration directly
 * from sdc.properties./* w w  w.jav a  2s .  c  o  m*/
 *
 * @param runtimeInfo RuntimeInfo instance
 * @param newConfigs New set of config properties
 * @throws IOException
 */
public static void storeControlHubConfigs(RuntimeInfo runtimeInfo, Map<String, String> newConfigs)
        throws IOException {
    File configFile = new File(runtimeInfo.getDataDir(), SCH_CONF_OVERRIDE);
    Properties properties = new Properties();

    // Load existing properties from disk if they exists
    if (configFile.exists()) {
        try (FileReader reader = new FileReader(configFile)) {
            properties.load(reader);
        }
    }

    // Propagate updated configuration
    for (Map.Entry<String, String> entry : newConfigs.entrySet()) {
        if (entry.getValue() == null) {
            properties.remove(entry.getKey());
        } else {
            properties.setProperty(entry.getKey(), entry.getValue());
        }
    }

    // Store the new updated configuration back to disk
    try (FileWriter writer = new FileWriter(configFile)) {
        properties.store(writer, null);
    }
}

From source file:mas.MAS.java

/**
 * @param args the command line arguments
 *///w  w  w  .  j av  a 2  s .  co m
// for old version
public static void getData(int startIdx, int endIdx) {
    try {
        Properties prop = new Properties();
        prop.setProperty("AppId", "1df63064-efad-4bbd-a797-1131499b7728");
        prop.setProperty("ResultObjects", "publication");
        prop.setProperty("DomainID", "22");
        prop.setProperty("SubDomainID", "2");
        prop.setProperty("YearStart", "2001");
        prop.setProperty("YearEnd", "2010");
        prop.setProperty("StartIdx", startIdx + "");
        prop.setProperty("EndIdx", endIdx + "");

        String url_org = "http://academic.research.microsoft.com/json.svc/search";
        String url_str = generateURL(url_org, prop);
        URL url = new URL(url_str);
        URLConnection yc = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        }
        in.close();
    } catch (MalformedURLException ex) {
        Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.linkedin.kmf.common.Utils.java

/**
 * Create the topic that the monitor uses to monitor the cluster.  This method attempts to create a topic so that all
 * the brokers in the cluster will have partitionToBrokerRatio partitions.  If the topic exists, but has different parameters
 * then this does nothing to update the parameters.
 *
 * TODO: Do we care about rack aware mode?  I would think no because we want to spread the topic over all brokers.
 * @param zkUrl zookeeper connection url
 * @param topic topic name//from   w ww.j a  v  a 2s . co m
 * @param replicationFactor the replication factor for the topic
 * @param partitionToBrokerRatio This is multiplied by the number brokers to compute the number of partitions in the topic.
 * @param topicConfig additional parameters for the topic for example min.insync.replicas
 * @return the number of partitions created
 */
public static int createMonitoringTopicIfNotExists(String zkUrl, String topic, int replicationFactor,
        double partitionToBrokerRatio, Properties topicConfig) {
    ZkUtils zkUtils = ZkUtils.apply(zkUrl, ZK_SESSION_TIMEOUT_MS, ZK_CONNECTION_TIMEOUT_MS,
            JaasUtils.isZkSecurityEnabled());
    try {
        if (AdminUtils.topicExists(zkUtils, topic)) {
            LOG.info("Monitoring topic \"" + topic + "\" already exists.");
            return getPartitionNumForTopic(zkUrl, topic);
        }

        int brokerCount = zkUtils.getAllBrokersInCluster().size();

        int partitionCount = (int) Math.ceil(brokerCount * partitionToBrokerRatio);

        int defaultMinIsr = Math.max(replicationFactor - 1, 1);
        if (!topicConfig.containsKey(KafkaConfig.MinInSyncReplicasProp())) {
            topicConfig.setProperty(KafkaConfig.MinInSyncReplicasProp(), Integer.toString(defaultMinIsr));
        }

        try {
            AdminUtils.createTopic(zkUtils, topic, partitionCount, replicationFactor, topicConfig,
                    RackAwareMode.Enforced$.MODULE$);
        } catch (TopicExistsException tee) {
            //There is a race condition with the consumer.
            LOG.info("Monitoring topic \"" + topic + "\" already exists (caught exception).");
            return getPartitionNumForTopic(zkUrl, topic);
        }
        LOG.info("Created monitoring topic \"" + topic + "\" with " + partitionCount
                + " partitions, min ISR of " + topicConfig.get(KafkaConfig.MinInSyncReplicasProp())
                + " and replication factor of " + replicationFactor + ".");

        return partitionCount;
    } finally {
        zkUtils.close();
    }
}

From source file:kr.co.bitnine.octopus.frame.SessionServerTest.java

private static Connection getConnection(String user, String password) throws Exception {
    InetSocketAddress addr = NetUtils.createSocketAddr("127.0.0.1:58000");
    String url = "jdbc:octopus://" + NetUtils.getHostPortString(addr);

    Properties info = new Properties();
    info.setProperty("user", user);
    info.setProperty("password", password);

    //        info.setProperty("prepareThreshold", "-1");
    info.setProperty("prepareThreshold", "1");

    //        info.setProperty("binaryTransfer", "true");

    return DriverManager.getConnection(url, info);
}

From source file:fr.msch.wissl.server.Library.java

private static void stfuLog4j() {
    Properties props = new Properties();
    // props.setProperty("org.jaudiotagger.level",
    // Level.WARNING.toString());
    props.setProperty(".level", Level.OFF.toString());
    // props.setProperty("handlers",
    // "java.util.logging.ConsoleHandler,java.util.logging.FileHandler");
    try {//from  ww  w. ja va2  s . c o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        props.store(baos, null);
        byte[] data = baos.toByteArray();
        baos.close();
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        LogManager.getLogManager().readConfiguration(bais);
    }

    catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.aepik.alasca.core.ldap.Schema.java

/**
 * Returns objects identifiers./*w  w  w.  j a va 2  s.co  m*/
 * @param oids SchemaObject array
 * @return Properties All objects identifiers.
 */
public static Properties getObjectsIdentifiers(SchemaObject[] oids) {
    Properties objectsIdentifiers = new Properties();
    for (SchemaObject object : oids) {
        String[] keys = object.getKeys();
        SchemaValue value = object.getValue(keys[0]);
        objectsIdentifiers.setProperty(keys[0], value.toString());
    }
    return objectsIdentifiers;
}

From source file:com.revorg.goat.IndexManager.java

/**
 * Creates documents inside of the Lucene Index
 *
 * @param driverName        Database Driver
 * @param sourceURL         Database Connection URL
 * @param dbUsername        Database Username
 * @param dbPassword        Database Password
 * @param execSQL           T-SQL//w  w  w.j ava2  s  .com
 * @throws Exception
 * @return ActionResult
 */
public static String indexDatabase(String indexPath, String driverName, String sourceURL, String dbUsername,
        String dbPassword, String execSQL) {
    //
    execSQL = execSQL.replace("from", "FROM");
    execSQL = execSQL.replace("FROM", " FROM ");
    String returnResult = "";
    String workPath = indexPath + dirSep + "working" + new Random().nextInt(100000) + dirSep;
    String configFile = indexPath + dirSep + "config" + dirSep + "dsschema.xml";
    String tempHTMLDir = tempDirectory + dirSep + "htmlIndexing" + dirSep + Utilities.CreateUUID() + dirSep;

    File workDir = new File(workPath);
    File schemaFile = new File(configFile);
    File htmlIndexing = new File(tempHTMLDir);

    // Declare the JDBC objects.
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsMetaData = null;

    try {

        //Get Configuration File
        if (schemaFile.exists() == false) {

            ActionResultError = "DB Schema File (" + schemaFile + ")Does Not Exists";
            System.out.println(ActionResultError);
            ActionResult = "Failure ";
            return ActionResult + ActionResultError;
        }

        //Make Sure Working Director Does Not Exists
        if (workDir.exists()) {
            ActionResultError = "Failure to create index: " + workPath + " The index/directory already exists:";
            ActionResult = "Failure";
            return ActionResult + ActionResultError;
        } else {
            //Create Temporary Index
            IndexManager.createIndex(workPath);
        }

        //Load the driver class
        Class.forName(driverName);
        System.out.println("Driver Loaded");
        Properties prop = new Properties();
        prop.setProperty("user", dbUsername);
        prop.setProperty("password", dbPassword);

        DriverManager.setLoginTimeout(5); //Set Login Time
        con = DriverManager.getConnection(sourceURL, prop);

        //Result Set
        // Create and execute an SQL statement that returns some data.
        String SQL = execSQL;
        stmt = con.createStatement();
        rs = stmt.executeQuery(SQL);
        rsMetaData = rs.getMetaData();
        int columns = rsMetaData.getColumnCount();
        String[] indexTypeArray = new String[columns];
        String[] columnNamesArray = new String[columns]; //Set array Length to Column Length from Meta Data
        String[] columnTypesArray = new String[columns]; //Set array Length to Column Length from Meta Data

        int primaryKeyPos = 0;
        int triggerPos = 0;
        String triggerType = "";
        boolean triggerExists = false;
        boolean primaryExists = false;

        XMLReader readerXML = new XMLReader(); //XML Reader Class   
        //Drop into an array to keep from parsing XML more than once
        for (int i = 0; i < columns; i++) {
            indexTypeArray[i] = readerXML.getNodeValueByFile(configFile, i, "indextype");
            columnNamesArray[i] = readerXML.getNodeValueByFile(configFile, i, "columnname");
            columnTypesArray[i] = readerXML.getNodeValueByFile(configFile, i, "columntype");
            //Get Trigger Position 
            if (indexTypeArray[i].equalsIgnoreCase("PrimaryKey") == true) {
                primaryExists = true;
                primaryKeyPos = i + 1;
            }
            //Update or Delete Trigger
            if (indexTypeArray[i].equalsIgnoreCase("triggerUpdate") == true
                    || indexTypeArray[i].equalsIgnoreCase("triggerDelete") == true) {
                triggerExists = true;
                triggerPos = i + 1;

                //Update or Delete Trigger
                if (indexTypeArray[i].equalsIgnoreCase("triggerUpdate") == true) {
                    triggerType = "Update";
                } else {
                    triggerType = "Delete";
                }

            }
        }

        //Create Temporary HTML Indexing Folder
        if (htmlIndexing.exists()) {
            ActionResultError = "Failure to create directory: " + htmlIndexing
                    + " The index/directory already exists:";
            ActionResult = "Failure";
            return ActionResult + ActionResultError;
        } else {
            //Create Temporary Index
            IndexManager.createIndex(tempHTMLDir);
        }

        Date start = new Date();
        //StandardAnalyzer new StandardAnalyzer() = new StandardAnalyzer();    //Initialize Class
        IndexWriter writer = new IndexWriter(workPath, new StandardAnalyzer(), false,
                IndexWriter.MaxFieldLength.LIMITED);
        System.out.println("Indexing to directory '" + workPath + "'...");

        String dynamicSQL = "";
        int currentRow = 0; //Process Next Rows                   
        while (rs.next()) {
            //Create Dynamic SQL
            if (primaryKeyPos != 0) {
                if (currentRow > 0) {
                    dynamicSQL = dynamicSQL + ",";
                }
                dynamicSQL = dynamicSQL + rs.getInt(primaryKeyPos);
            }

            String docStatus = createDocument(writer, rs, columnNamesArray, indexTypeArray, tempHTMLDir);

            //On Failure
            if (docStatus.substring(0, 4).equalsIgnoreCase("Fail")) {
                IndexManager.deleteIndex(tempHTMLDir);

                IndexManager.deleteIndex(workPath);
                return docStatus;
            }

            //Create Actual Document  
            ++currentRow;
        }

        returnResult = "Successfully indexing of " + Integer.toString(currentRow) + " documents.";

        //Get Table From String
        //System.out.println(execSQL);
        String updateTable = "";
        String[] words = execSQL.split(" ");
        int wordPos = 0;
        int tablePos = 0;
        for (String word : words) {
            ++wordPos;
            if (word.equalsIgnoreCase("FROM") == true) {
                tablePos = wordPos + 2;
            }
            if (tablePos == wordPos) {
                updateTable = word;
                break;
            }
        }

        //Must be Records
        if (triggerExists && primaryExists && updateTable.length() > 0 && currentRow != 0) {

            if (triggerType.equalsIgnoreCase("Update") == true) {
                dynamicSQL = "update " + updateTable + " set " + columnNamesArray[triggerPos - 1] + " =1 where "
                        + columnNamesArray[primaryKeyPos - 1] + " in (" + dynamicSQL + ");";
            } else {
                dynamicSQL = "delete from " + updateTable + " where " + columnNamesArray[primaryKeyPos - 1]
                        + " in (" + dynamicSQL + ");";
            }
            System.out.println(dynamicSQL);
            stmt.execute(dynamicSQL);
        }

        System.out.println("Optimizing..." + currentRow + " Documents");

        //Close Working Writer
        writer.close();

        //Merge Indexes;
        IndexManager.mergeIndexes(indexPath, workPath);
        //Optimization Done Inside Merge

        //Delete Working Folder
        IndexManager.deleteIndex(workPath);
        IndexManager.deleteIndex(tempHTMLDir);

        Date end = new Date();
        System.out.println(end.getTime() - start.getTime() + " total milliseconds: = "
                + ((end.getTime() - start.getTime()) / 1000) + " Seconds");

        ActionResult = returnResult;
        rs.close(); //Close Result Set
        con.close();
        return ActionResult;

    }

    catch (Exception e) {
        IndexManager.deleteIndex(workPath); //Delete Working Folder
        IndexManager.deleteIndex(tempHTMLDir);

        e.printStackTrace();
        ActionResult = "Failure: " + e + " caught a " + e.getClass() + " with message: " + e.getMessage();
        return ActionResult + ActionResultError;

    }
}

From source file:net.sourceforge.czt.gnast.Gnast.java

/**
 * Returns a property list of all the properties in <code>props</code>
 * that start with the given <code>prefix</code>.
 * Furthermore, the values of both properties are equal.
 *
 * @param prefix //from  w w w.  j  a v a  2  s.  c o m
 * @param props 
 * @return should never be <code>null</code>.
 */
public static Properties withPrefix(String prefix, Properties props) {
    Properties result = new Properties();
    for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
        String propertyName = (String) e.nextElement();
        if (propertyName.startsWith(prefix))
            result.setProperty(propertyName, props.getProperty(propertyName));
    }
    return result;
}

From source file:de.dal33t.powerfolder.util.ConfigurationLoader.java

/**
 * Merges the give pre configuration properties into the target config
 * properties. It can be choosen if existing keys in the target properties
 * should be replaced or not.// w ww. ja v  a  2s.c o m
 *
 * @param preConfig
 *            the pre config
 * @param targetConfig
 *            the config file to set the pre-configuration values into.
 * @param replaceExisting
 *            if existing key/value pairs will be overwritten by pairs of
 *            pre config.
 * @return the number of merged entries.
 */
private static int mergeConfigs(Properties preConfig, Properties targetConfig, boolean replaceExisting) {
    Reject.ifNull(preConfig, "PreConfig is null");
    Reject.ifNull(targetConfig, "TargetConfig is null");
    int n = 0;
    for (Object obj : preConfig.keySet()) {
        String key = (String) obj;
        String value = preConfig.getProperty(key);
        if (!targetConfig.containsKey(key) || replaceExisting) {
            Object oldValue = targetConfig.setProperty(key, value);
            if (!key.startsWith(PREFERENCES_PREFIX) && !value.equals(oldValue)) {
                n++;
            }
            LOG.finer("Preconfigured " + key + "=" + value);
        }
    }
    if (n > 0) {
        LOG.fine(n + " default configurations set");
    } else {
        LOG.finer("No additional default configurations set");
    }
    return n;
}

From source file:XMLUtils.java

/**
 * Returns a Properties object matching the given node.
 * @param ns the namespace./*from   w w  w .j a  v  a2 s .co m*/
 * @param base the element from where to search.
 * @param name of the element to get.
 * @return the value of this element.
 */
public static Properties getPropertiesValueElement(final String ns, final Element base, final String name) {
    Properties returnedProperties = new Properties();

    // Get element
    NodeList list = base.getElementsByTagNameNS(ns, name);
    if (list.getLength() == 1) {
        Element element = (Element) list.item(0);

        // Get property element
        NodeList properties = element.getElementsByTagNameNS(ns, "property");

        // If properties is present, analyze them and add them
        if (properties.getLength() > 0) {
            for (int i = 0; i < properties.getLength(); i++) {
                Element elemProperty = (Element) properties.item(i);
                String pName = getAttributeValue(elemProperty, "name");
                String pValue = getAttributeValue(elemProperty, "value");
                if (pName != null && pValue != null) {
                    returnedProperties.setProperty(pName, pValue);
                }

            }
        }
    } else if (list.getLength() > 1) {
        throw new IllegalStateException("Element '" + name + "' on '" + base
                + "' should be unique but there are '" + list.getLength() + "' elements");
    }

    return returnedProperties;
}