Example usage for java.util Properties get

List of usage examples for java.util Properties get

Introduction

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

Prototype

@Override
    public Object get(Object key) 

Source Link

Usage

From source file:com.baomidou.framework.spring.MutilPropertyPlaceholderConfigurer.java

/**
 * <p>//from  w  w w  .  j a  v a  2s.  co m
 * ? prop 
 * </p>
 * @param mergeProperties
 *                spring  Properties 
 * @return
 */
protected Properties convertMergeProperties(Properties mergeProperties) {
    Properties prop = new Properties();
    String runMode = "_" + getRunMode() + "_mode";
    Set<Entry<Object, Object>> es = mergeProperties.entrySet();
    for (Entry<Object, Object> entry : es) {
        String key = (String) entry.getKey();
        String realKey = key;
        int idx = key.lastIndexOf("_mode");
        if (idx > 0) {
            if (key.contains(runMode)) {
                realKey = key.substring(0, key.lastIndexOf(runMode));
            } else {
                /** ?? */
                realKey = null;
            }
        }
        /**
         * ??<br>
         * ??
         */
        if (realKey != null && !prop.containsKey(realKey)) {
            Object value = null;
            if (idx > 0) {
                value = mergeProperties.get(realKey + runMode);
            } else {
                value = mergeProperties.get(realKey);
            }
            if (value != null) {
                prop.put(realKey, value);
            } else {
                throw new SpringWindException("impossible empty property for " + realKey);
            }
        }
    }
    return prop;
}

From source file:emp.cloud.pigutils.EmbeddedPigRunner.java

static int executeScript(Configuration hadoopConfig, PigProgressNotificationListener listener, String taskName,
        String script) throws Throwable {

    boolean verbose = false;
    boolean gruntCalled = false;
    String logFileName = null;/*www  .j a  v a2  s . com*/

    try {
        Properties properties = new Properties();
        PropertiesUtil.loadDefaultProperties(properties);
        properties.putAll(ConfigurationUtil.toProperties(hadoopConfig));

        HashSet<String> optimizerRules = new HashSet<String>();
        ExecType execType = ExecType.MAPREDUCE;

        if (properties.getProperty("aggregate.warning") == null) {
            // by default warning aggregation is on
            properties.setProperty("aggregate.warning", "" + true);
        }

        if (properties.getProperty("opt.multiquery") == null) {
            // by default multiquery optimization is on
            properties.setProperty("opt.multiquery", "" + true);
        }

        if (properties.getProperty("stop.on.failure") == null) {
            // by default we keep going on error on the backend
            properties.setProperty("stop.on.failure", "" + false);
        }

        // set up client side system properties in UDF context
        UDFContext.getUDFContext().setClientSystemProps(properties);

        // create the context with the parameter
        PigContext pigContext = new PigContext(execType, properties);

        // create the static script state object

        ScriptState scriptState = ScriptState.start("", pigContext);

        if (listener != null) {
            scriptState.registerListener(listener);
        }

        if (!Boolean.valueOf(properties.getProperty(PROP_FILT_SIMPL_OPT, "false"))) {
            // turn off if the user has not explicitly turned on this
            // optimization
            optimizerRules.add("FilterLogicExpressionSimplifier");
        }

        if (optimizerRules.size() > 0) {
            pigContext.getProperties().setProperty("pig.optimizer.rules",
                    ObjectSerializer.serialize(optimizerRules));
        }

        if (properties.get("udf.import.list") != null)
            PigContext.initializeImportList((String) properties.get("udf.import.list"));

        PigContext.setClassLoader(pigContext.createCl(null));
        pigContext.getProperties().setProperty(PigContext.JOB_NAME, taskName);

        Grunt grunt = null;
        BufferedReader in;
        scriptState.setScript(script);
        in = new BufferedReader(new StringReader(script));

        grunt = new Grunt(in, pigContext);
        gruntCalled = true;
        int results[] = grunt.exec();

        return getReturnCodeForStats(results);

        //      } catch (Exception e) {
        //         if (e instanceof PigException) {
        //            PigException pe = (PigException) e;
        //            int rc = (pe.retriable()) ? ReturnCode.RETRIABLE_EXCEPTION
        //                  : ReturnCode.PIG_EXCEPTION;
        //            PigStatsUtil.setErrorCode(pe.getErrorCode());
        //         }
        //         PigStatsUtil.setErrorMessage(e.getMessage());
        //
        //         if (!gruntCalled) {
        //            LogUtils.writeLog(e, logFileName, log, verbose,
        //                  "Error before Pig is launched");
        //         }
        //         FileLocalizer.deleteTempFiles();
        //
        //         if (!gruntCalled) {
        //            LogUtils.writeLog(e, logFileName, log, verbose,
        //                  "Error before Pig is launched");
        //         }
        //         throw e;
        //      } catch (Throwable e) {
        //         PigStatsUtil.setErrorMessage(e.getMessage());
        //         throw new IllegalStateException(e);
    } finally {
        // clear temp files
        FileLocalizer.deleteTempFiles();
    }
}

From source file:com.noelios.restlet.ext.jdbc.JdbcClientHelper.java

/**
 * Returns a JDBC connection./* ww  w .  java 2  s .c  om*/
 * 
 * @param uri
 *            The connection URI.
 * @param properties
 *            The connection properties.
 * @param usePooling
 *            Indicates if the connection pooling should be used.
 * @return The JDBC connection.
 * @throws SQLException
 */
protected Connection getConnection(String uri, Properties properties, boolean usePooling) throws SQLException {
    Connection result = null;

    if (usePooling) {
        for (final ConnectionSource c : this.connectionSources) {
            // Check if the connection URI is identical
            // and if the same number of properties is present
            if ((result == null) && c.getUri().equalsIgnoreCase(uri)
                    && (properties.size() == c.getProperties().size())) {
                // Check that the properties tables are equivalent
                boolean equal = true;
                for (final Object key : c.getProperties().keySet()) {
                    if (equal && properties.containsKey(key)) {
                        equal = equal && (properties.get(key).equals(c.getProperties().get(key)));
                    } else {
                        equal = false;
                    }
                }

                if (equal) {
                    result = c.getConnection();
                }
            }
        }

        if (result == null) {
            // No existing connection source found
            final ConnectionSource cs = new ConnectionSource(uri, properties);
            this.connectionSources.add(cs);
            result = cs.getConnection();
        }
    } else {
        result = DriverManager.getConnection(uri, properties);
    }

    return result;
}

From source file:com.granule.json.utils.internal.JSONObject.java

/**
 * Internal method to write out a proper JSON attribute string.
 * @param writer The writer to use while serializing
 * @param attrs The attributes in a properties object to write out
 * @param depth How far to indent the JSON text.
 * @param compact Whether or not to use pretty indention output, or compact output, format
 * @throws IOException Trhown if an error occurs on write.
 *///from  ww w  .j a  v a2 s.  c om
private void writeAttributes(Writer writer, Properties attrs, int depth, boolean compact) throws IOException {
    if (logger.isLoggable(Level.FINER))
        logger.entering(className, "writeAttributes(Writer, Properties, int, boolean)");

    if (attrs != null) {
        Enumeration props = attrs.propertyNames();

        if (props != null && props.hasMoreElements()) {
            while (props.hasMoreElements()) {
                String prop = (String) props.nextElement();
                writeAttribute(writer, escapeAttributeNameSpecialCharacters(prop), (String) attrs.get(prop),
                        depth + 1, compact);
                if (props.hasMoreElements()) {
                    try {
                        if (!compact) {
                            writer.write(",\n");
                        } else {
                            writer.write(",");
                        }
                    } catch (Exception ex) {
                        IOException iox = new IOException("Error occurred on serialization of JSON text.");
                        iox.initCause(ex);
                        throw iox;
                    }
                }
            }
        }
    }

    if (logger.isLoggable(Level.FINER))
        logger.exiting(className, "writeAttributes(Writer, Properties, int, boolean)");
}

From source file:com.wallabystreet.kinjo.common.transport.ws.ServiceDescriptor.java

/**
 * Loads the transport-specific service-related properties and stores them
 * in the service descriptor's <code>properties</code> field.
 * <p />//from   ww  w.  j a va2s. co  m
 * This method expects a class
 * <ul>
 * <li>named <code>Transport</code>
 * <li>with a public default (no parameter, that is) constructor</li>
 * <li>which implements the <code>TransportDescriptor</code> interface
 * </ul>
 * in the package name specified in the argument. It creates a new instance
 * of this class, calls the
 * {@link com.wallabystreet.kinjo.common.transport.protocol.TransportDescriptor#getServiceRelatedProperties(String, String)}
 * method on it and copies all key/value pairs from the result into the
 * service descriptor's <code>properties</code> field.
 * 
 * @param transportPackage
 *            The package containing the <code>Transport</code> class used
 *            for configuration.
 * @throws MalformedTransportException,
 *             IIF the <code>Transport</code> class is missing,
 *             inaccessible or incompatible.
 * 
 * @see com.wallabystreet.kinjo.common.transport.protocol.TransportDescriptor
 * @see com.wallabystreet.kinjo.common.transport.protocol.TransportDescriptor#getServiceRelatedProperties(String,
 *      String)
 */
private void loadTransportSpecificConfiguration(String transportPackage) throws MalformedTransportException {
    // constant for the transport class and package name
    final String transportPackageName = transportPackage.trim();
    final String transportClassName = "Transport";

    TransportDescriptor d = null;
    try {
        d = (TransportDescriptor) Class.forName(transportPackageName + "." + transportClassName).newInstance();
    } catch (InstantiationException e) {
        String msg = "instantiation failed: " + transportPackageName + "." + transportClassName;
        if (log.isWarnEnabled()) {
            log.warn(msg, e);
        }
        throw new MalformedTransportException(msg);
    } catch (IllegalAccessException e) {
        String msg = "illegal access: " + transportPackageName + "." + transportClassName;
        if (log.isWarnEnabled()) {
            log.warn(msg, e);
        }
        throw new MalformedTransportException(msg);
    } catch (ClassNotFoundException e) {
        String msg = "class not found: " + transportPackageName + "." + transportClassName;
        if (log.isWarnEnabled()) {
            log.warn(msg, e);
        }
        throw new MalformedTransportException(msg);
    }

    Properties p = d.getServiceRelatedProperties(this.name, this.pkg);
    Enumeration e = p.propertyNames();
    while (e.hasMoreElements()) {
        String property = (String) e.nextElement();
        /*
         * since we don't know whether the returned properties are
         * java.lang.String instances, we have to use the generic
         * java.util.Hashtable methods to get and set the properties
         */
        this.properties.put(property, p.get(property));
    }
}

From source file:com.aol.advertising.qiao.emitter.KafkaEmitter.java

private Properties buildProperties() {
    Properties props = new Properties();
    props.put(PROP_BROKER_LIST, brokerList);
    props.put(PROP_REQUEST_REQUIRED_ACKS, ackPolicy.value);
    props.put(PROP_MSG_MAX_RETRIES, String.valueOf(msgSendMaxRetries));
    props.put(PROP_CLIENT_ID, clientId);
    props.put(PROP_REQUEST_REQUIRED_ACKS, ackPolicy.value);

    if (serializerClassname != null)
        props.put(PROP_SERIALIZER_CLASS, serializerClassname);
    if (keySerializerClassname != null)
        props.put(PROP_KEY_SERIALIZER_CLASS, keySerializerClassname);

    if (partitionerClassname != null)
        props.put(PROP_PARTITIONER_CLASS, partitionerClassname);
    else {/*from  w  ww . jav  a2s . c om*/
        String val = (String) props.get(PROP_PARTITIONER_CLASS);
        if (val == null || val.length() == 0) {
            props.put(PROP_PARTITIONER_CLASS, DEFAULT_PARTITIONER_CLASSNAME);
            logger.info("Kafka Producer uses non-sticky round-robin partitioner.");
        }
    }
    if (producerType != null)
        props.put(PROP_PRODUCER_TYPE, producerType);
    if (messagesPerBatch > 0)
        props.put(PROP_BATCH_NUM_MSGS, String.valueOf(messagesPerBatch));
    if (messagesBatchTimeoutMS > 0)
        props.put(PROP_BATCH_BUFFERING_MAX_MS, String.valueOf(messagesBatchTimeoutMS));
    if (maxMessagesBuffering > 0)
        props.put(PROP_QUEUE_BUFFERING_MAX_MESSAGES, String.valueOf(maxMessagesBuffering));
    if (sendBufferBytes > 0)
        props.put(PROP_SEND_BUFFER_BYTES, String.valueOf(sendBufferBytes));

    String prop_path = CommonUtils.getQiaoConfigDir() + File.separator + KAFKA_PROPERTY_FILE;
    File prop_file = new File(prop_path);
    Properties props2 = loadProperties(prop_file);
    if (props2 != null)
        props.putAll(props2);

    return props;
}

From source file:com.photon.phresco.impl.DrupalApplicationProcessor.java

private void storeConfigObj(List<Configuration> configs, File featureManifestXmlFile, File featureSqlDir,
        String environmentName) throws PhrescoException {
    try {//from   w w w  .  j av a  2  s .com
        if (!featureManifestXmlFile.isFile()) {
            throw new PhrescoException("manifest file is not available");
        }

        // Document
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(featureManifestXmlFile);
        doc.getDocumentElement().normalize();

        // xpath
        XPathFactory factory = XPathFactory.newInstance();
        XPath xPathInstance = factory.newXPath();

        for (Configuration configuration : configs) {
            Properties properties = configuration.getProperties();
            Enumeration em = properties.keys();
            while (em.hasMoreElements()) {
                String insertQuery = "";
                String insertFieldQuery = "";

                String deleteQuery = "";
                String deleteFieldQuery = "";

                String tableName = "";
                String variableName = "";
                String defaultValue = "";

                String constructedQuery = "";
                String key = (String) em.nextElement();
                Object object = properties.get(key);

                // get config object for this key
                String xPathQuery = CONFIG_XPATH + key + CONFIG_XPATH_END_TAG;
                XPathExpression xPathExpression = xPathInstance.compile(xPathQuery);
                //evalute the xpath query in the entire xml document and define the return type
                Object results = xPathExpression.evaluate(doc, XPathConstants.NODESET);
                NodeList nList = (NodeList) results;

                // config objects
                for (int i = 0; i < nList.getLength(); i++) {
                    Node nNode = nList.item(i);
                    // get config object values
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        // getting child nodes to construct query
                        NodeList childNodes = nNode.getChildNodes();
                        for (int temp1 = 0; temp1 < childNodes.getLength(); temp1++) {
                            Node childNode = childNodes.item(temp1);
                            if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                                if (TABLE_NAME.equals(childNode.getNodeName())) {
                                    tableName = childNode.getTextContent();
                                    if (!VARIABLE_FIELD.equals(tableName)) {
                                        return;
                                    }
                                    deleteQuery = deleteQuery + DELETE_FROM + childNode.getTextContent() + WHERE
                                            + NAME_FIELD + EQUAL;
                                    insertQuery = insertQuery + INSERT_INTO + childNode.getTextContent()
                                            + VARIABLE_START_TAG + NAME_FIELD + SQL_VARIABLE_SEP + VALUE_FIELD
                                            + VARIABLE_END_TAG + VALUES_START_TAG;
                                } else if (VARIABLE_NAME.equals(childNode.getNodeName())) {
                                    variableName = childNode.getTextContent();
                                    deleteFieldQuery = SINGLE_QUOTE + childNode.getTextContent() + SINGLE_QUOTE
                                            + SEMI_COLON + LINE_BREAK;
                                } else if (CURRENT_VALUE.equals(childNode.getNodeName())) {
                                    childNode.setTextContent(object.toString());
                                }
                                defaultValue = object.toString();
                                insertFieldQuery = variableName + SQL_VALUE_SEP + defaultValue + VALUES_END_TAG;
                            }
                        }
                    }
                }

                constructedQuery = deleteQuery + deleteFieldQuery + insertQuery + insertFieldQuery;

                List<File> sqlFolders = getSqlFolders(featureSqlDir);
                for (File sqlFolder : sqlFolders) {
                    replaceSqlBlock(sqlFolder, CONFIGURATION + environmentName + DOT_SQL, key,
                            constructedQuery);
                }
            }
        }
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(doc), new StreamResult(featureManifestXmlFile.getPath()));
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
}

From source file:br.com.ingenieux.mojo.beanstalk.AbstractNeedsEnvironmentMojo.java

protected ConfigurationOptionSetting[] introspectOptionSettings() {
    Set<ConfigurationOptionSetting> configOptionSetting = new TreeSet<ConfigurationOptionSetting>(
            COS_COMPARATOR);//from www.  j ava2s .c om

    Properties properties = new Properties();

    if (null != project) {
        for (Map.Entry<Object, Object> entry : project.getProperties().entrySet()) {
            if (("" + entry.getKey()).startsWith("beanstalk")) {
                properties.put(entry.getKey(), entry.getValue());
            }
        }
    }

    for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
        if (("" + entry.getKey()).startsWith("beanstalk")) {
            properties.put(entry.getKey(), entry.getValue());
        }
    }

    for (Object o : properties.keySet()) {
        String k = "" + o;

        if (k.startsWith("beanstalk.env.aws.")) {
            String realKey = k.substring("beanstalk.env.".length());
            String v = "" + properties.get(k);
            List<String> elements = new ArrayList<String>(Arrays.asList(realKey.split("\\.")));

            String namespace = StringUtils.join(elements.subList(0, -1 + elements.size()), ":");
            String optionName = elements.get(-1 + elements.size());

            getLog().info("importing " + k + " as " + namespace + ":" + optionName + "=" + v);

            configOptionSetting.add(new ConfigurationOptionSetting().withNamespace(namespace)
                    .withOptionName(optionName).withValue(v));
        } else if (COMMON_PARAMETERS.containsKey(k)) {
            String v = "" + properties.get(k);
            String namespace = COMMON_PARAMETERS.get(k).getNamespace();
            String optionName = COMMON_PARAMETERS.get(k).getOptionName();

            getLog().info("Found alias " + k + " for " + namespace + ":" + optionName + "(value=" + v + ")");

            configOptionSetting.add(new ConfigurationOptionSetting().withNamespace(namespace)
                    .withOptionName(optionName).withValue(v));
        }
    }

    return (ConfigurationOptionSetting[]) configOptionSetting
            .toArray(new ConfigurationOptionSetting[configOptionSetting.size()]);
}

From source file:com.mirth.connect.server.controllers.DefaultExtensionController.java

@Override
public void initPlugins() {
    // Order all the plugins by their weight before loading any of them.
    Map<String, String> pluginNameMap = new HashMap<String, String>();
    NavigableMap<Integer, List<String>> weightedPlugins = new TreeMap<Integer, List<String>>();
    for (PluginMetaData pmd : getPluginMetaData().values()) {
        if (isExtensionEnabled(pmd.getName())) {
            if (pmd.getServerClasses() != null) {
                for (PluginClass pluginClass : pmd.getServerClasses()) {
                    String clazzName = pluginClass.getName();
                    int weight = pluginClass.getWeight();
                    pluginNameMap.put(clazzName, pmd.getName());

                    List<String> classList = weightedPlugins.get(weight);
                    if (classList == null) {
                        classList = new ArrayList<String>();
                        weightedPlugins.put(weight, classList);
                    }//from  w ww  .j av  a2 s  . c  o m

                    classList.add(clazzName);
                }
            }
        } else {
            logger.warn("Plugin \"" + pmd.getName() + "\" is not enabled.");
        }
    }

    // Load the plugins in order of their weight
    for (List<String> classList : weightedPlugins.descendingMap().values()) {
        for (String clazzName : classList) {
            String pluginName = pluginNameMap.get(clazzName);

            try {
                ServerPlugin serverPlugin = (ServerPlugin) Class.forName(clazzName).newInstance();

                if (serverPlugin instanceof ServicePlugin) {
                    ServicePlugin servicePlugin = (ServicePlugin) serverPlugin;
                    /*
                     * load any properties that may currently be in the database
                     */
                    Properties currentProperties = getPluginProperties(pluginName);
                    /* get the default properties for the plugin */
                    Properties defaultProperties = servicePlugin.getDefaultProperties();

                    /*
                     * if there are any properties that not currently set, set them to the the
                     * default
                     */
                    for (Object key : defaultProperties.keySet()) {
                        if (!currentProperties.containsKey(key)) {
                            currentProperties.put(key, defaultProperties.get(key));
                        }
                    }

                    /* save the properties to the database */
                    setPluginProperties(pluginName, currentProperties);

                    /*
                     * initialize the plugin with those properties and add it to the list of
                     * loaded plugins
                     */
                    servicePlugin.init(currentProperties);
                    servicePlugins.put(servicePlugin.getPluginPointName(), servicePlugin);
                    serverPlugins.add(servicePlugin);
                    logger.debug("sucessfully loaded server plugin: " + serverPlugin.getPluginPointName());
                }

                if (serverPlugin instanceof ChannelPlugin) {
                    ChannelPlugin channelPlugin = (ChannelPlugin) serverPlugin;
                    channelPlugins.put(channelPlugin.getPluginPointName(), channelPlugin);
                    serverPlugins.add(channelPlugin);
                    logger.debug(
                            "sucessfully loaded server channel plugin: " + serverPlugin.getPluginPointName());
                }

                if (serverPlugin instanceof CodeTemplateServerPlugin) {
                    CodeTemplateServerPlugin codeTemplateServerPlugin = (CodeTemplateServerPlugin) serverPlugin;
                    codeTemplateServerPlugins.put(codeTemplateServerPlugin.getPluginPointName(),
                            codeTemplateServerPlugin);
                    serverPlugins.add(codeTemplateServerPlugin);
                    logger.debug("sucessfully loaded server code template plugin: "
                            + serverPlugin.getPluginPointName());
                }

                if (serverPlugin instanceof DataTypeServerPlugin) {
                    DataTypeServerPlugin dataTypePlugin = (DataTypeServerPlugin) serverPlugin;
                    dataTypePlugins.put(dataTypePlugin.getPluginPointName(), dataTypePlugin);
                    serverPlugins.add(dataTypePlugin);
                    logger.debug(
                            "sucessfully loaded server data type plugin: " + serverPlugin.getPluginPointName());
                }

                if (serverPlugin instanceof ResourcePlugin) {
                    ResourcePlugin resourcePlugin = (ResourcePlugin) serverPlugin;
                    resourcePlugins.put(resourcePlugin.getPluginPointName(), resourcePlugin);
                    serverPlugins.add(resourcePlugin);
                    logger.debug("Successfully loaded resource plugin: " + resourcePlugin.getPluginPointName());
                }

                if (serverPlugin instanceof TransmissionModeProvider) {
                    TransmissionModeProvider transmissionModeProvider = (TransmissionModeProvider) serverPlugin;
                    transmissionModeProviders.put(transmissionModeProvider.getPluginPointName(),
                            transmissionModeProvider);
                    serverPlugins.add(transmissionModeProvider);
                    logger.debug("Successfully loaded transmission mode provider plugin: "
                            + transmissionModeProvider.getPluginPointName());
                }

                if (serverPlugin instanceof AuthorizationPlugin) {
                    AuthorizationPlugin authorizationPlugin = (AuthorizationPlugin) serverPlugin;

                    if (this.authorizationPlugin != null) {
                        throw new Exception("Multiple Authorization Plugins are not permitted.");
                    }

                    this.authorizationPlugin = authorizationPlugin;
                    serverPlugins.add(authorizationPlugin);
                    logger.debug("sucessfully loaded server authorization plugin: "
                            + serverPlugin.getPluginPointName());
                }
            } catch (Exception e) {
                logger.error("Error instantiating plugin: " + pluginName, e);
            }
        }
    }
}