Example usage for java.util Properties getProperty

List of usage examples for java.util Properties getProperty

Introduction

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

Prototype

public String getProperty(String key) 

Source Link

Document

Searches for the property with the specified key in this property list.

Usage

From source file:com.springframework.core.io.support.SpringFactoriesLoader.java

/**
 * Load the fully qualified class names of factory implementations of the
 * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given
 * class loader./*from   w  w  w  . j  av a2 s.  c  o m*/
 * @param factoryClass the interface or abstract class representing the factory
 * @param classLoader the ClassLoader to use for loading resources; can be
 * {@code null} to use the default
 * @see #loadFactories
 * @throws IllegalArgumentException if an error occurs while loading factory names
 */
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    try {
        Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION)
                : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        List<String> result = new ArrayList<String>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
            String factoryClassNames = properties.getProperty(factoryClassName);
            result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
        }
        return result;
    } catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load [" + factoryClass.getName()
                + "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}

From source file:Main.java

public static void getParam(String filename) {
    Properties props = new Properties();
    File file = new File(filename);
    try {//www  . j a v a2 s. co m
        props.load(new FileInputStream(file));
        //         String value = props.getProperty(key);
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        dbUser = props.getProperty("dbUser");
        dbPwd = props.getProperty("dbPwd");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.api.MMXVersionResourceTest.java

@BeforeClass
public static void setupDatabase() throws Exception {
    java.util.logging.Logger.getLogger("com.google.inject").setLevel(java.util.logging.Level.SEVERE);
    org.apache.log4j.Logger.getLogger("org.apache.http").setLevel(org.apache.log4j.Level.DEBUG);
    org.apache.log4j.Logger.getLogger("org.jboss.resteasy").setLevel(Level.OFF);
    InputStream inputStream = MMXTopicTagsResourceTest.class.getResourceAsStream("/test.properties");

    Properties testProperties = new Properties();
    testProperties.load(inputStream);//from  w w  w  . j a  va  2  s. c  o  m

    String host = testProperties.getProperty("db.host");
    String port = testProperties.getProperty("db.port");
    String user = testProperties.getProperty("db.user");
    String password = testProperties.getProperty("db.password");
    String driver = testProperties.getProperty("db.driver");
    String schema = testProperties.getProperty("db.schema");

    String url = "jdbc:mysql://" + host + ":" + port + "/" + schema;

    ds = new BasicDataSource();
    ds.setDriverClassName(driver);
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setUrl(url);

    DBTestUtil.setBasicDataSource(ds);
    new MockUp<AppDAOImpl>() {
        @Mock
        protected String getEncrypted(String value) {
            return value;
        }
    };
    DBTestUtil.setupMockDBUtil();
    appEntity = createRandomApp();
    LOGGER.warn("Finished setupDatabase");
}

From source file:net.ageto.gyrex.impex.persistence.cassandra.ConfigureRepositoryPreferences.java

/**
 * Trys to read the value with the given key from p. when found it stores
 * the value in the given repository properties
 *
 * @param p//from  ww w  .  j  a va  2  s.  c  o m
 *            the p
 * @param key
 *            the key
 * @param repositoryPreferences
 *            the non secure repository preferences
 * @return the and set property
 */
private static void getAndSetProperty(final Properties p, final String key,
        final IRepositoryPreferences repositoryPreferences) {
    final String value = p.getProperty(key);
    if (value != null) {
        repositoryPreferences.put(key, value, false);
    }
}

From source file:Main.java

public static String readData(Context mContext, String key, int resId) {
    Properties props = new Properties();
    try {/*from w w w  . j a  v  a 2  s .  c o m*/
        InputStream in = new BufferedInputStream(mContext.getResources().openRawResource(resId));
        props.load(in);
        in.close();
        String value = props.getProperty(key);
        return value;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.db.TopicDaoImplTest.java

@BeforeClass
public static void setupDatabase() throws Exception {
    InputStream inputStream = DeviceDAOImplTest.class.getResourceAsStream("/test.properties");

    Properties testProperties = new Properties();
    testProperties.load(inputStream);//  w w  w  . ja  v  a2  s.co m

    String host = testProperties.getProperty("db.host");
    String port = testProperties.getProperty("db.port");
    String user = testProperties.getProperty("db.user");
    String password = testProperties.getProperty("db.password");
    String driver = testProperties.getProperty("db.driver");
    String schema = testProperties.getProperty("db.schema");

    String url = "jdbc:mysql://" + host + ":" + port + "/" + schema;

    ds = new BasicDataSource();
    ds.setDriverClassName(driver);
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setUrl(url);

    DBTestUtil.setBasicDataSource(ds);
}

From source file:com.metamx.emitter.core.Emitters.java

public static Emitter create(Properties props, HttpClient httpClient, ObjectMapper jsonMapper,
        Lifecycle lifecycle) {//from w w  w  .  j  a  va2  s  . c o m
    Map<String, Object> jsonified = Maps.newHashMap();

    if (props.getProperty(LOG_EMITTER_PROP) != null) {
        jsonified.put("logging", makeLoggingMap(props));
    } else if (props.getProperty(HTTP_EMITTER_PROP) != null) {
        jsonified.put("http", makeHttpMap(props));
    } else {
        throw new ISE("Unknown type of emitter. Please set [%s] or [%s]", LOG_EMITTER_PROP, HTTP_EMITTER_PROP);
    }

    return jsonMapper.convertValue(jsonified, EmitterBuilder.class).build(jsonMapper, httpClient, lifecycle);
}

From source file:ezbake.data.postgres.hibernate.HibernateUtil.java

private static SessionFactory buildSessionFactory(Properties ezConfig, EzSecurityToken token,
        SessionType sessionType) {//  ww w . j  a  v a2  s.c o  m
    try {
        String appName = ezConfig.getProperty(EzBakePropertyConstants.EZBAKE_APPLICATION_NAME);
        switch (sessionType) {
        case EZBAKE: {

            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
            for (Map.Entry<Object, Object> entry : ezConfig.entrySet()) {
                String key = (String) entry.getKey();
                String value = (String) entry.getValue();

                configuration.setProperty("hibernate.connection." + key, value);
            }

            return configuration
                    .setProperty("hibernate.connection.driver_class", "ezbake.data.postgres.EzPostgresDriver")
                    .setProperty("hibernate.connection.username",
                            ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_USERNAME))
                    .setProperty("hibernate.connection.password",
                            ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PASSWORD))
                    .setProperty("hibernate.connection.url",
                            String.format("jdbc:ezbake:postgresql://%s:%s/%s",
                                    ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_HOST),
                                    ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PORT), appName))
                    .setProperty("hibernate.default_schema", "public")
                    .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect")
                    .setProperty("EzSecurityToken",
                            new String(Base64.encodeBase64(new TSerializer().serialize(token)),
                                    Charsets.US_ASCII))
                    .setProperty("hibernate.hbm2ddl.auto", "update").configure().buildSessionFactory();
        }
        case POSTGRES: {
            return new Configuration().setProperty("hibernate.connection.driver_class", "org.postgresql.Driver")
                    .setProperty("hibernate.connection.username",
                            ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_USERNAME))
                    .setProperty("hibernate.connection.password",
                            ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PASSWORD))
                    .setProperty("hibernate.connection.url",
                            String.format("jdbc:postgresql://%s:%s/%s",
                                    ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_HOST),
                                    ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PORT), appName))
                    .setProperty("hibernate.default_schema", "public")
                    .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect")
                    .setProperty("hibernate.show_sql", "true").setProperty("hibernate.hbm2ddl.auto", "update")
                    .configure().buildSessionFactory();
        }
        default: {
            throw new Exception("Invalid session type [" + sessionType + "].");
        }
        }
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.cloud.utils.ProcessUtil.java

public static void pidCheck(String pidDir, String run) throws ConfigurationException {

    String dir = pidDir == null ? "/var/run" : pidDir;

    try {/*from  ww  w .j  a  va2s. c  o m*/
        final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
        if (propsFile == null) {
            s_logger.debug("environment.properties could not be opened");
        } else {
            final Properties props = PropertiesUtil.loadFromFile(propsFile);
            dir = props.getProperty("paths.pid");
            if (dir == null) {
                dir = pidDir == null ? "/var/run" : pidDir;
            }
        }
    } catch (IOException e) {
        s_logger.debug("environment.properties could not be opened");
    }

    final File pidFile = new File(dir + File.separator + run);
    try {
        if (!pidFile.createNewFile()) {
            if (!pidFile.exists()) {
                throw new ConfigurationException("Unable to write to " + pidFile.getAbsolutePath()
                        + ".  Are you sure you're running as root?");
            }

            final String pidLine = FileUtils.readFileToString(pidFile).trim();
            if (pidLine.isEmpty()) {
                throw new ConfigurationException(
                        "Java process is being started twice.  If this is not true, remove "
                                + pidFile.getAbsolutePath());
            }
            try {
                final long pid = Long.parseLong(pidLine);
                final Script script = new Script("bash", 120000, s_logger);
                script.add("-c", "ps -p " + pid);
                final String result = script.execute();
                if (result == null) {
                    throw new ConfigurationException(
                            "Java process is being started twice.  If this is not true, remove "
                                    + pidFile.getAbsolutePath());
                }
                if (!pidFile.delete()) {
                    throw new ConfigurationException(
                            "Java process is being started twice.  If this is not true, remove "
                                    + pidFile.getAbsolutePath());
                }
                if (!pidFile.createNewFile()) {
                    throw new ConfigurationException(
                            "Java process is being started twice.  If this is not true, remove "
                                    + pidFile.getAbsolutePath());
                }
            } catch (final NumberFormatException e) {
                throw new ConfigurationException(
                        "Java process is being started twice.  If this is not true, remove "
                                + pidFile.getAbsolutePath());
            }
        }
        pidFile.deleteOnExit();

        final Script script = new Script("bash", 120000, s_logger);
        script.add("-c", "echo $PPID");
        final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
        script.execute(parser);

        final String pid = parser.getLine();

        FileUtils.writeStringToFile(pidFile, pid + "\n");
    } catch (final IOException e) {
        throw new CloudRuntimeException(
                "Unable to create the " + pidFile.getAbsolutePath() + ".  Are you running as root?", e);
    }
}

From source file:net.ripe.rpki.validator.util.TrustAnchorLocator.java

private static TrustAnchorLocator readExtendedTrustAnchorLocator(File file, String contents)
        throws IOException, URISyntaxException {
    Properties p = new Properties();
    p.load(new StringReader(contents));

    String caName = p.getProperty("ca.name");
    String loc = p.getProperty("certificate.location");
    Validate.notEmpty(loc, "'certificate.location' must be provided");
    URI location = new URI(loc);
    String publicKeyInfo = p.getProperty("public.key.info", "").replaceAll("\\s+", "");
    String[] uris = p.getProperty("prefetch.uris", "").split(",");
    List<URI> prefetchUris = new ArrayList<URI>(uris.length);
    for (String uri : uris) {
        uri = uri.trim();/*w ww.  j a v  a  2s . co m*/
        if (StringUtils.isNotBlank(uri)) {
            if (!uri.endsWith("/") && uri.startsWith("rsync://")) {
                uri += "/";
            }
            prefetchUris.add(new URI(uri));
        }
    }
    return new TrustAnchorLocator(file, caName, location, publicKeyInfo, prefetchUris);
}