Example usage for java.util Properties store

List of usage examples for java.util Properties store

Introduction

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

Prototype

public void store(OutputStream out, String comments) throws IOException 

Source Link

Document

Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the #load(InputStream) load(InputStream) method.

Usage

From source file:org.fusesource.cloudmix.agent.InstallerAgent.java

private synchronized boolean persistProperties(Properties props, String filePath) {

    try {/*from  ww  w.j  a v  a  2 s.  com*/
        if (props == null || filePath == null || "".equals(filePath)) {
            return false;
        }
        File propFile = new File(filePath);
        if (!propFile.exists()) {
            if (propFile.getParentFile() != null && !propFile.getParentFile().exists()) {
                FileUtils.createDirectory(propFile.getParentFile());
            }
            propFile.createNewFile();
        }

        props.store(new FileOutputStream(propFile), "agent details as of " + new Date());
        return true;
    } catch (Exception e) {
        LOG.warn("error storing properties file " + filePath, e);
        return false;
    }
}

From source file:au.com.jwatmuff.eventmanager.gui.main.LoadCompetitionWindow.java

private void loadBackupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadBackupButtonActionPerformed
    File databaseStore = new File(Main.getWorkingDirectory(), "comps");
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter("Event Manager Files", "evm"));

    JPanel optionsPanel = new JPanel();

    optionsPanel.setBorder(//from  w  w w  .java  2s .co  m
            new CompoundBorder(new EmptyBorder(0, 10, 0, 10), new TitledBorder("Load backup options")));
    JCheckBox preserveIDCheckbox = new JCheckBox("Preserve competition ID");
    optionsPanel.add(preserveIDCheckbox);

    chooser.setAccessory(optionsPanel);

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        /* input zip file */
        File file = chooser.getSelectedFile();
        /* construct output directory */
        File dir = new File(databaseStore, file.getName());
        int suffix = 0;
        while (dir.exists()) {
            suffix++;
            dir = new File(databaseStore, file.getName() + "_" + suffix);
        }
        /* unzip */
        try {
            ZipUtils.unzipFile(dir, file);

            /* change id */
            Properties props = new Properties();
            FileReader fr = new FileReader(new File(dir, "info.dat"));
            props.load(fr);
            fr.close();
            if (!preserveIDCheckbox.isSelected()) {
                props.setProperty("UUID", UUID.randomUUID().toString());
            }
            props.setProperty("name", props.getProperty("name") + " - " + dateFormat.format(new Date()));
            FileWriter fw = new FileWriter(new File(dir, "info.dat"));
            props.store(fw, "");
            fw.close();

            /* update gui */
            checkDatabasesExecutor.schedule(checkDatabasesTask, 0, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            GUIUtils.displayError(null, "Error while opening file: " + e.getMessage());
        }
    }
}

From source file:org.hupo.psi.mi.psicquic.view.webapp.controller.config.PsicquicViewConfig.java

public void saveConfigToFile() throws IOException {
    Properties properties = new Properties();

    if (new File(configFile).exists()) {
        properties.load(new FileInputStream(configFile));
    }//w  ww .  jav  a  2s  . c o m

    setProperty(properties, "title", title);
    setProperty(properties, "logo.url", logoUrl);
    setProperty(properties, "banner.background.url", bannerBackgroundUrl);
    setProperty(properties, "registry.tags", registryTagsAsString);
    setProperty(properties, "registry.url", registryURL);
    setProperty(properties, "query.filter", miqlFilterQuery);
    setProperty(properties, "services.included", includedServices);
    setProperty(properties, "services.excluded", excludedServices);
    setProperty(properties, "clustering.limit.count", String.valueOf(clusteringSizeLimit));
    setProperty(properties, "services.rows", String.valueOf(serviceRows));
    setProperty(properties, "colour.schema", colourSchema);
    setProperty(properties, "download.all.storage.location", downloadAllLocation);
    setProperty(properties, "download.all.limit.count", String.valueOf(downloadAllSizeLimit));

    OutputStream outputStream = new FileOutputStream(configFile);
    properties.store(outputStream, "Configuration updated: " + new Date());
    outputStream.close();
}

From source file:com.iver.utiles.connections.ConnectionDB.java

/**
 * Keeps in disk the data of the connection
 * // w  ww .ja  v a  2s .  com
 * @param ct
 *            Data connection
 * 
 * @throws IOException
 */
public void setPersistence(ConnectionTrans ct) throws IOException {
    String name = ct.getHost() + "_" + ct.getName();
    Properties properties = new Properties();
    properties.put("jdbc.drivers", ct.getDriver());
    properties.put("jdbc.name", ct.getName());
    properties.put("jdbc.host", ct.getHost());
    properties.put("jdbc.port", ct.getPort());
    properties.put("jdbc.username", ct.getUser());
    properties.put("jdbc.savepassword", String.valueOf(ct.isSavePassword()));

    if (ct.isSavePassword()) {
        properties.put("jdbc.password", ct.getPassword());
    }

    properties.put("jdbc.database", ct.getDb());
    properties.put("jdbc.connBeginning", ct.getConnBeginning());
    boolean success = true;
    File file = null;

    String directory = FileUtils.getAppHomeDir() + "connections";

    if (!new File(directory).exists()) {
        file = new File(directory);
        success = file.mkdirs();
    }

    if (success) {
        File f = new File(directory + File.separator + name + ".properties");
        f.createNewFile();

        FileOutputStream out = new FileOutputStream(f);
        properties.store(out, name);
        out.close();
    }
}

From source file:com.twinsoft.convertigo.engine.Context.java

private boolean saveProperties(String path, Properties properties) {
    File file = new File(path);
    // Creates file if needed
    if (!file.exists()) {
        try {//www.j av  a 2s .  c  o  m
            if (file.createNewFile()) {
                Engine.logContext.warn("File '" + path + "' has been created");
            } else {
                Engine.logContext.warn("Problems occured while creating file  '" + path + "'");
            }
        } catch (Exception e) {
            Engine.logContext.error("Problems occured while creating file  '" + path + "'", e);
        }
    }
    // Store properties to file
    if (file.exists()) {
        try {
            FileOutputStream fos = new FileOutputStream(file);
            properties.store(fos, "");
            fos.flush();
            fos.close();
            return true;
        } catch (FileNotFoundException e) {
            Engine.logContext.warn(
                    "Problems occured while saving properties '" + name + "': file  '" + path + "' not found!");
        } catch (IOException e) {
            Engine.logContext.error(
                    "Problems occured while saving properties '" + name + "' to  file  '" + path + "'", e);
        }
    }
    return false;
}

From source file:be.ac.ua.comp.scarletnebula.core.CloudProvider.java

/**
 * Saves the file describing this CloudProvider. If a cloudprovider by the
 * name "providername" already exists, the savefile will be overwritten.
 * /*w  w w . jav  a 2s .  c  o  m*/
 */
public void store() {
    // First assure the providers/ directory exists
    final File dir = new File("providers");

    if (!dir.exists() || !dir.isDirectory()) {
        if (!dir.mkdir()) {
            log.error("Could not create providers/ directory.");
        }
    }

    // Now write to the file properties file
    final Properties prop = new Properties();

    prop.setProperty("class", providerClassName);
    prop.setProperty("apikey", apiKey);
    prop.setProperty("apisecret", apiSecret);
    prop.setProperty("endpoint", endpoint);
    prop.setProperty("defaultKeypair", defaultKeypair);
    prop.setProperty("favoriteImages", getSerialisedFavoriteImages());

    try {
        prop.store(new FileOutputStream(getConfigfileName(name)), null);
    } catch (final Exception e) {
        log.error("Properties file describing cloud provider could not be created.");
    }
}

From source file:com.adito.jdbc.DBUpgrader.java

/**
 * Check the database schema and perform any upgrades.
 * /*  w  ww.  j av a2 s . c  o m*/
 * @throws Exception on any error
 */
public void upgrade() throws Exception {
    Properties versions = null;
    if (versionsFile == null) {
        /* If required, convert from the old preferences node to the new
         * file (version 0.2.5)
         */
        versionsFile = new File(ContextHolder.getContext().getDBDirectory(), "versions.log");
        Preferences p = ContextHolder.getContext().getPreferences().node("dbupgrader");
        if (p.nodeExists("currentDataVersion")) {
            log.warn("Migrating database versions from preferences to properties file in "
                    + ContextHolder.getContext().getDBDirectory().getAbsolutePath() + ".");
            versions = new Properties();
            p = p.node("currentDataVersion");
            String[] c = p.keys();
            for (int i = 0; i < c.length; i++) {
                versions.put(c[i], p.get(c[i], ""));
            }
            FileOutputStream fos = new FileOutputStream(versionsFile);
            try {
                versions.store(fos, "Database versions");
            } finally {
                Util.closeStream(fos);
            }
            p.removeNode();
        }
    }

    // Load the database versions
    if (versions == null) {
        versions = new Properties();
        if (versionsFile.exists()) {
            FileInputStream fin = new FileInputStream(versionsFile);
            try {
                versions.load(fin);
            } finally {
                Util.closeStream(fin);
            }
        }
    }

    try {
        String dbCheckName = useDbNameForVersionCheck ? engine.getDatabase() : engine.getAlias();

        if ((!engine.isDatabaseExists() || removed.containsKey(engine.getDatabase()))
                && !removeProcessed.containsKey(dbCheckName)) {
            versions.remove(dbCheckName);
            removeProcessed.put(dbCheckName, Boolean.TRUE);
            if (log.isInfoEnabled())
                log.info("Database for " + dbCheckName + " (" + engine.getDatabase()
                        + ") has been removed, assuming this is a re-install.");
            removed.put(engine.getDatabase(), Boolean.TRUE);
        }

        // Check for any SQL scripts to run to bring the databases up to
        // date
        VersionInfo.Version currentDataVersion = new VersionInfo.Version(
                versions.getProperty(dbCheckName, "0.0.0"));
        if (log.isInfoEnabled()) {
            log.info("New logical database version for " + engine.getAlias() + " is " + newDbVersion);
            log.info("Current logical database version for " + engine.getAlias() + " is " + currentDataVersion);
            //
            log.info("Upgrade script directory is " + upgradeDir.getAbsolutePath());
        }
        List upgrades = getSortedUpgrades(upgradeDir);
        File oldLog = new File(upgradeDir, "upgrade.log");
        if (!dbDir.exists()) {
            if (!dbDir.mkdirs()) {
                throw new Exception("Failed to create database directory " + dbDir.getAbsolutePath());
            }
        }
        File logFile = new File(dbDir, "upgrade.log");
        if (oldLog.exists()) {
            if (log.isInfoEnabled())
                log.info(
                        "Moving upgrade.log to new location (as of version 0.1.5 it resides in the db directory.");
            if (!oldLog.renameTo(logFile)) {
                throw new Exception("Failed to move upgrade log file from " + oldLog.getAbsolutePath() + " to "
                        + logFile.getAbsolutePath());
            }
        }
        HashMap completedUpgrades = new HashMap();
        if (!logFile.exists()) {
            OutputStream out = null;
            try {
                out = new FileOutputStream(logFile);
                PrintWriter writer = new PrintWriter(out, true);
                writer.println("# This file contains a list of database upgrades");
                writer.println("# that have completed correctly.");
            } finally {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            }
        } else {
            InputStream in = null;
            try {
                in = new FileInputStream(logFile);
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (!line.equals("") && !line.startsWith("#")) {
                        completedUpgrades.put(line, line);
                    }
                }
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        }
        OutputStream out = null;
        try {
            out = new FileOutputStream(logFile, true);
            PrintWriter writer = new PrintWriter(out, true);
            Class.forName("org.hsqldb.jdbcDriver"); // shouldnt be needed,
            // but
            // just in
            // case
            for (Iterator i = upgrades.iterator(); i.hasNext();) {
                DBUpgradeOp upgrade = (DBUpgradeOp) i.next();
                boolean runBefore = completedUpgrades.containsKey(upgrade.getFile().getName());
                if (log.isInfoEnabled())
                    log.info("Checking if upgrade " + upgrade.getFile() + " [" + upgrade.getVersion()
                            + "] needs to be run. Run before = " + runBefore + ". Current data version = "
                            + currentDataVersion + ", upgrade version = " + upgrade.getVersion());
                if ((!runBefore || (currentDataVersion.getMajor() == 0 && currentDataVersion.getMinor() == 0
                        && currentDataVersion.getBuild() == 0))
                        && upgrade.getVersion().compareTo(currentDataVersion) >= 0
                        && upgrade.getVersion().compareTo(newDbVersion) < 0) {
                    if (log.isInfoEnabled())
                        log.info("Running script " + upgrade.getName() + " [" + upgrade.getVersion()
                                + "] on database " + engine.getDatabase());

                    // Get a JDBC connection
                    JDBCConnectionImpl conx = engine.aquireConnection();
                    try {
                        runSQLScript(conx, upgrade.getFile());
                        completedUpgrades.put(upgrade.getFile().getName(), upgrade.getFile().getName());
                        writer.println(upgrade.getFile().getName());
                    } finally {
                        engine.releaseConnection(conx);
                    }
                }
            }
            versions.put(dbCheckName, newDbVersion.toString());

            if (log.isInfoEnabled())
                log.info("Logical database " + engine.getAlias() + " (" + engine.getDatabase()
                        + ") is now at version " + newDbVersion);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    } finally {
        FileOutputStream fos = new FileOutputStream(versionsFile);
        try {
            versions.store(fos, "Database versions");
        } finally {
            Util.closeStream(fos);
        }
    }
}

From source file:com.edgenius.wiki.installation.UpgradeServiceImpl.java

@SuppressWarnings("unused")
private void up2130To2140() throws Exception {
    log.info("Version 2.13 to 2.14 is upgarding");

    //detect server.properties, add 2 new attributes, if mail user is not empty, also enable auth attribute
    String root = DataRoot.getDataRoot();
    if (FileUtil.exist(root + Server.FILE)) {
        Properties prop = FileUtil.loadProperties(root + Server.FILE);
        prop.setProperty("mail.smtp.jndi", "");
        prop.setProperty("mail.smtp.properties", "");

        Server server = new Server();
        server.syncFrom(prop);//from   w  ww. ja va  2 s.  com
        if (!StringUtils.isEmpty(server.getMailUsername())) { //?? should also check password?
            server.setMailProperties("mail.smtp.auth:true");
        }

        server.syncTo(prop);
        prop.store(FileUtil.getFileOutputStream(root + Server.FILE), "save by system program");
    }
}

From source file:net.java.jpatch.maven.ReleaseMojo.java

/**
 * Creates the release package./*from  w w w .  jav  a 2s .  c o  m*/
 * 
 * @throws MojoExecutionException if the method fails.
 * @throws MojoFailureException if the method fails.
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    // Search for existing release
    Artifact releaseArtifact = resolveReleaseArtifact();
    File releaseFile = releaseArtifact.getFile();

    // Check existing release
    if (releaseFile != null && releaseFile.exists()) {
        getLog().info(releaseFile.getAbsolutePath());
        getLog().error("Release file already exist! For new release execute first jpatch:release-clean.");
        throw new MojoFailureException("Release package already exist!");
    }

    // Create release directory
    File directory = createTargetDirectory(releaseArtifact.getVersion());

    // Create release properties file.
    Properties releaseProperties = new Properties();

    // Load projects
    List<MavenProject> mavenProjects = loadMavenProjects();

    // Filter the projects
    List<MavenProject> filterProjects = filterMavenProjects(mavenProjects, getPackages());

    // Unpack the libraries in the output directory
    for (MavenProject project : filterProjects) {

        String revision = scmRevision(project);
        releaseProperties.setProperty(project.getId(), revision);

        Artifact artifact = project.getArtifact();
        resolveArtifactFromLocalRepository(artifact);
        unpackArtifactFile(directory, artifact.getFile());
    }

    // Setup the advanced properties to the release property
    SimpleDateFormat sdf = new SimpleDateFormat();
    releaseProperties.put(RELEASE_PROPERTY_DATE, sdf.format(new Date()));
    releaseProperties.put(RELEASE_PROPERTY_USER_NAME, SystemUtils.USER_NAME);
    releaseProperties.put(RELEASE_PROPERTY_JAVA_VERSION, SystemUtils.JAVA_VERSION);
    releaseProperties.put(RELEASE_PROPERTY_OS_NAME, SystemUtils.OS_NAME);

    // Save release properties file
    try {
        File propFile = new File(mavenProject.getBuild().getDirectory(),
                mavenProject.getBuild().getFinalName() + ".properties");
        releaseProperties.store(new FileOutputStream(propFile), null);
    } catch (IOException e) {
        throw new MojoExecutionException("Error creating the release properties file!", e);
    }

    // Create package file
    String fileName = mavenProject.getBuild().getFinalName();
    File packFile = new File(mavenProject.getBuild().getDirectory(), fileName + ".zip");
    packDirectory(directory, packFile);

    // Attached the package to the project
    releaseArtifact.setFile(packFile);
    mavenProject.addAttachedArtifact(releaseArtifact);

    // Create build file (project.jpatch)
    createBuildFile();
}

From source file:com.jaspersoft.studio.statistics.UsageManager.java

/**
 * Write a property on the installation informations properties file. The property is written only if there isn't a
 * property with the same key and value already save. After and if the property is written the file is saved in the
 * disk/*from w w w .j ava2 s  .c o  m*/
 * 
 * @param propertyName
 *          the name of the property to write, must be not null
 * @param newValue
 *          the value of the property to write
 */
protected void setInstallationInfo(String propertyName, String newValue) {
    synchronized (UsageManager.this) {
        Properties info = getInstallationInfoContainer();
        String value = info.getProperty(propertyName);
        boolean equals = value == null ? newValue == null : value.equals(newValue);
        if (!equals) {
            FileOutputStream out = null;
            try {
                // Write the property only if there isn't a previous one with the same value
                info.setProperty(propertyName, newValue);
                File appDataFolder = getAppDataFolder();
                File propertiesFile = new File(appDataFolder, INFO_FILE_NAME);
                out = new FileOutputStream(propertiesFile.getAbsolutePath());
                info.store(out,
                        "Installation information - This information are NEVER send to the statistics server, used only locally for configuration purpose"); //$NON-NLS-1$
            } catch (Exception ex) {
                ex.printStackTrace();
                JaspersoftStudioPlugin.getInstance().logError(Messages.UsageManager_errorWriteInfoProperties,
                        ex);
            } finally {
                FileUtils.closeStream(out);
            }
        }
    }
}