Example usage for org.springframework.core.io.support PropertiesLoaderUtils loadProperties

List of usage examples for org.springframework.core.io.support PropertiesLoaderUtils loadProperties

Introduction

In this page you can find the example usage for org.springframework.core.io.support PropertiesLoaderUtils loadProperties.

Prototype

public static Properties loadProperties(Resource resource) throws IOException 

Source Link

Document

Load properties from the given resource (in ISO-8859-1 encoding).

Usage

From source file:com.mulodo.hadoop.wordcount.Application.java

public static void main(String[] args) throws IOException {

    Resource resource = new ClassPathResource("application.properties");
    Properties props = PropertiesLoaderUtils.loadProperties(resource);

    System.out.println(props.getProperty("spring.hadoop.fsUri"));
    System.out.println(props.getProperty("spring.hadoop.resourceManagerHost"));
    System.out.println(props.getProperty("spring.hadoop.jobHistoryAddress"));

    SpringApplication.run(Application.class, args);
}

From source file:com.moreopen.config.center.ConfigCenterLauncher.java

public static void main(String[] args) throws Exception {
    final String PROFILE_NAME = "/app.properties";
    Properties properties = PropertiesLoaderUtils
            .loadProperties(new UrlResource(ConfigCenterLauncher.class.getResource(PROFILE_NAME)));
    int port = Integer.parseInt(properties.getProperty("webserver.port"));
    if (port == 0) {
        logger.error("property: config.webserver.port not found, please check " + PROFILE_NAME);
        return;/*from   www .j a v a 2s . c  o m*/
    }
    // launch the monitor console server
    new ConfigCenterLauncher(port).run();
    server.join();
}

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Main method.//  w  w  w  . j  a va2  s .c  o  m
 */
public static void main(String args[]) {
    LogUtils.setupUncaughtExceptionHandler();

    /* Set timeout for RMI connections - TODO: move to external file */
    System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000");
    updateRmiHostName();

    /*
     * Set up menu bar for Mac
     */
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager");

    /*
     * Set look and feel to 'system' style
     */
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.info("Failed to set system look and feel");
    }

    /*
     * Set workingDir to a writable folder for storing competitions, settings etc.
     */
    String applicationData = System.getenv("APPDATA");
    if (applicationData != null) {
        workingDir = new File(applicationData, "EventManager");
        if (workingDir.exists() || workingDir.mkdirs()) {
            // redirect logging to writable folder
            LogUtils.reconfigureFileAppenders("log4j.properties", workingDir);
        } else {
            workingDir = new File(".");
        }
    }

    // log version for debugging
    log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")");

    /*
     * Copy license if necessary
     */
    File license1 = new File("license.lic");
    File license2 = new File(workingDir, "license.lic");
    if (license1.exists() && !license2.exists()) {
        try {
            FileUtils.copyFile(license1, license2);
        } catch (IOException e) {
            log.warn("Failed to copy license from " + license1 + " to " + license2, e);
        }
    }
    if (license1.exists() && license2.exists()) {
        if (license1.lastModified() > license2.lastModified()) {
            try {
                FileUtils.copyFile(license1, license2);
            } catch (IOException e) {
                log.warn("Failed to copy license from " + license1 + " to " + license2, e);
            }
        }
    }

    /*
     * Check if run lock exists, if so ask user if it is ok to continue
     */
    if (!obtainRunLock(false)) {
        int response = JOptionPane.showConfirmDialog(null,
                "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?",
                "Run-lock detected", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION)
            obtainRunLock(true);
        else
            System.exit(0);
    }

    try {
        LoadWindow loadWindow = new LoadWindow();
        loadWindow.setVisible(true);

        loadWindow.addMessage("Reading settings..");

        /*
         * Read properties from file
         */
        final Properties props = new Properties();
        try {
            Properties defaultProps = PropertiesLoaderUtils
                    .loadProperties(new ClassPathResource("eventmanager.properties"));
            props.putAll(defaultProps);
        } catch (IOException ex) {
            log.error(ex);
        }

        props.putAll(System.getProperties());

        File databaseStore = new File(workingDir, "comps");
        int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port"));

        loadWindow.addMessage("Loading Peer Manager..");
        log.info("Loading Peer Manager");

        ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService();
        JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat"));
        peerManager.addDiscoveryService(manualDiscoveryService);

        monitorNetworkInterfaceChanges(peerManager);

        loadWindow.addMessage("Loading Database Manager..");
        log.info("Loading Database Manager");

        DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager);
        LicenseManager licenseManager = new LicenseManager(workingDir);

        loadWindow.addMessage("Loading Load Competition Dialog..");
        log.info("Loading Load Competition Dialog");

        LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager,
                peerManager);
        loadCompetitionWindow.setTitle(WINDOW_TITLE);

        loadWindow.dispose();
        log.info("Starting Load Competition Dialog");

        while (true) {
            // reset permission checker to use our license
            licenseManager.updatePermissionChecker();

            GUIUtils.runModalJFrame(loadCompetitionWindow);

            if (loadCompetitionWindow.getSuccess()) {
                DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo();

                if (!databaseManager.checkLock(info.id)) {
                    String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n"
                            + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n"
                            + "3) Delete the competition from this computer\n"
                            + "4) If possible, reload this competition from another computer on the network\n"
                            + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked.";
                    String title = "WARNING: Potential Data Corruption Detected";

                    int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION,
                            JOptionPane.ERROR_MESSAGE, null,
                            new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)");

                    if (status == 0)
                        continue; // return to load competition window
                }

                SynchronizingWindow syncWindow = new SynchronizingWindow();
                syncWindow.setVisible(true);
                long t = System.nanoTime();
                DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash);
                long dt = System.nanoTime() - t;
                log.debug(String.format("Initial sync in %dms",
                        TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS)));
                syncWindow.dispose();

                if (loadCompetitionWindow.isNewDatabase()) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    Date today = calendar.getTime();
                    calendar.set(Calendar.MONTH, Calendar.DECEMBER);
                    calendar.set(Calendar.DAY_OF_MONTH, 31);
                    Date endOfYear = new java.sql.Date(calendar.getTimeInMillis());

                    CompetitionInfo ci = new CompetitionInfo();
                    ci.setName(info.name);
                    ci.setStartDate(today);
                    ci.setEndDate(today);
                    ci.setAgeThresholdDate(endOfYear);
                    //ci.setPasswordHash(info.passwordHash);
                    License license = licenseManager.getLicense();
                    if (license != null) {
                        ci.setLicenseName(license.getName());
                        ci.setLicenseType(license.getType().toString());
                        ci.setLicenseContact(license.getContactPhoneNumber());
                    }
                    database.add(ci);
                }

                // Set PermissionChecker to use database's license type
                String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType();
                PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType));

                TransactionNotifier notifier = new TransactionNotifier();
                database.setListener(notifier);

                MainWindow mainWindow = new MainWindow();
                mainWindow.setDatabase(database);
                mainWindow.setNotifier(notifier);
                mainWindow.setPeerManager(peerManager);
                mainWindow.setLicenseManager(licenseManager);
                mainWindow.setManualDiscoveryService(manualDiscoveryService);
                mainWindow.setTitle(WINDOW_TITLE);
                mainWindow.afterPropertiesSet();

                TestUtil.setActivatedDatabase(database);

                // show main window (modally)
                GUIUtils.runModalJFrame(mainWindow);

                // shutdown procedures

                // System.exit();

                database.shutdown();
                databaseManager.deactivateDatabase(1500);

                if (mainWindow.getDeleteOnExit()) {
                    for (File file : info.localDirectory.listFiles())
                        if (!file.isDirectory())
                            file.delete();
                    info.localDirectory.deleteOnExit();
                }
            } else {
                // This can cause an RuntimeException - Peer is disconnected
                peerManager.stop();
                System.exit(0);
            }
        }
    } catch (Throwable e) {
        log.error("Error in main function", e);
        String message = e.getMessage();
        if (message == null)
            message = "";
        if (message.length() > 100)
            message = message.substring(0, 97) + "...";
        GUIUtils.displayError(null,
                "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message);
        System.exit(0);
    }
}

From source file:com.betfair.tornjak.monitor.overlay.AuthFileReader.java

public static RolePerms load(Resource resource) throws IOException {
    Properties properties = PropertiesLoaderUtils.loadProperties(resource);

    // find all the roles we'll be using.
    String roles = properties.getProperty("jmx.roles");
    RolePerms rolePerms = new RolePerms();
    if (roles != null) {
        // now build up the list of perms
        for (String roleName : roles.split(",")) {
            roleName = StringUtils.trim(roleName);
            AccessRules accessRules = new AccessRules();
            // find all the entries for each role
            for (int i = 0; i < MAX_MATCHERS_PER_ROLE; i++) {
                String allowPrefix = String.format("role.%s.readAllow.%d.", roleName, i);
                String denyPrefix = String.format("role.%s.readDeny.%d.", roleName, i);

                accessRules.addMatcherAllowed(createMatcher(allowPrefix, properties));
                accessRules.addMatcherDisallowed(createMatcher(denyPrefix, properties));
            }//from w  w w.  ja v a  2s  .c om
            rolePerms.addAccessRules(roleName, accessRules);
        }
    }
    return rolePerms;
}

From source file:de.steilerdev.myVerein.server.apns.PushService.java

/**
 * This function creates a new APNS instance. If the function returns null, APNS is not supported.
 * @return The current APNS instance. If null APNS is not supported by this server.
 *///  w  w  w  .j av  a 2 s  . com
public static PushManager<SimpleApnsPushNotification> getInstanced() {
    if (pushManager == null) {
        logger.debug("Creating new APNS instance");
        try {
            Resource settingsResource = new ClassPathResource(apnsSettingsFile);
            Properties settings = PropertiesLoaderUtils.loadProperties(settingsResource);

            InputStream certFile = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(settings.getProperty(fileKey));

            pushManager = new PushManager<>(ApnsEnvironment.getSandboxEnvironment(),
                    SSLContextUtil.createDefaultSSLContext(certFile, settings.getProperty(passwordKey)), null, // Optional: custom event loop group
                    null, // Optional: custom ExecutorService for calling listeners
                    null, // Optional: custom BlockingQueue implementation
                    new PushManagerConfiguration(), "ExamplePushManager");

            logger.debug("Created new APNS instance, starting");
            //pushManager.start();
        } catch (IOException e) {
            logger.warn("Unable to load APNS settings file: {}", e.getMessage());
            return null;
        } catch (Exception e) {
            logger.warn("An unknown error occurred: {}", e.getMessage());
        }
    }
    logger.info("Returning APNS instance");
    return pushManager;
}

From source file:org.carewebframework.api.property.mock.MockPropertyService.java

/**
 * Constructor to allow initialization of property values from a property file. A property
 * values are assumed local unless the property name is prefixed with "global.". You may specify
 * an instance name by appending to the property name a "\" followed by the instance name. For
 * example://  ww  w .jav a2s  . c o m
 * 
 * <pre>
 *  prop1 = value1
 *  global.prop2 = value2
 *  prop3\inst3 = value3
 *  global.prop4\inst4 = value4
 * </pre>
 * 
 * @param resource Property file resource.
 * @throws IOException IO exception.
 */
public MockPropertyService(Resource resource) throws IOException {
    Properties props = PropertiesLoaderUtils.loadProperties(resource);

    for (Entry<?, ?> entry : props.entrySet()) {
        String key = (String) entry.getKey();
        String value = StringEscapeUtils.unescapeJava((String) entry.getValue());
        boolean global = key.startsWith("global.");
        key = global ? key.substring(7) : key;

        if (!key.contains(delim)) {
            key += delim;
        }

        (global ? global_map : local_map).put(key, value);
    }
}

From source file:org.zalando.stups.spring.boot.actuator.ExtInfoEndpointConfiguration.java

@Bean
public InfoEndpoint infoEndpoint() throws Exception {
    LinkedHashMap<String, Object> info = new LinkedHashMap<String, Object>();
    for (String filename : getAllPropertiesFiles()) {
        Resource resource = new ClassPathResource("/" + filename);
        Properties properties = new Properties();
        if (resource.exists()) {
            properties = PropertiesLoaderUtils.loadProperties(resource);
            String name = resource.getFilename();

            info.put(name.replace(PROPERTIES_SUFFIX, PROPERTIES_SUFFIX_REPLACEMENT),
                    Maps.fromProperties(properties));
        } else {/*from w ww  .j a v a2 s.  c o  m*/
            if (failWhenResourceNotExists()) {
                throw new RuntimeException("Resource : " + filename + " does not exist");
            } else {
                log.info("Resource {} does not exist", filename);
            }
        }
    }
    return new InfoEndpoint(info);
}

From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.restserver.reports.GenerateReportsRest.java

public Representation getHandler() {
    String result = null;//from  w w w  . java2 s .  c  o  m
    try {
        getParameters();

        // Generate Reports at MCC level for dates
        if (topAccountId != null && dateStart != null && dateEnd != null) {

            getContext().getParameters().add("maxThreads", "512");

            Resource resource = new ClassPathResource(file);
            if (!resource.exists()) {
                resource = new FileSystemResource(file);
            }
            DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);

            ReportProcessor processor = getApplicationContext().getBean(ReportProcessor.class);

            // Launching a new Service(Thread) to make the request async.
            RunnableReport runnableReport = new RunnableReport(topAccountId, processor, properties, dateStart,
                    dateEnd);

            taskService.submit(runnableReport);

            result = "OK - Task created, this usually takes 10-15mins for 1000 accounts/month";
        } else {
            taskService.getContext();
        }
    } catch (Exception exception) {
        return handleException(exception);
    }
    addReadOnlyHeaders();
    return createJsonResult(result);
}

From source file:com.thinkbiganalytics.scheduler.QuartzSchedulerClusterListener.java

private void validateQuartzClusterConfiguration() {
    Resource resource = new ClassPathResource("quartz.properties");
    if (resource.exists()) {
        try {//from  w  w w .  ja v a 2 s  . co m
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            Boolean isClustered = BooleanUtils
                    .toBoolean(properties.getProperty("org.quartz.jobStore.isClustered"));
            boolean isValid = isClustered;
            if (!isValid) {
                log.error(
                        "Kylo is running in clustered mode by Quartz scheduler is not configured for clustered mode.  Please ensure the Quartz is configured for database persistence in clustered mode ");
            }
        } catch (IOException e) {
            log.error(
                    "Kylo is running in Clustered mode the system cannot find the 'quartz.properties' file.  Please ensure the Quartz is configured for database persistence in clustered mode",
                    e);
        }
    } else {
        log.error(
                "Kylo is running in Clustered mode the system cannot find the 'quartz.properties' file. Please ensure the Quartz is configured for database persistence in clustered mode");
    }

}