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:au.com.jwatmuff.eventmanager.gui.main.LoadCompetitionWindow.java

private void renameCompButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renameCompButtonActionPerformed

    selected = (DatabaseInfo) competitionList.getSelectedValue();
    if (selected == null)
        return;/* w w w.  j  a v  a  2s  .  c  o m*/
    if (!Main.VERSION.equals(selected.version)) {
        GUIUtils.displayError(this, "This competition is only compatible with version " + selected.version
                + ".\nThis copy of EventManager is version " + Main.VERSION + ".");
        return;
    }

    String newName = (String) JOptionPane.showInputDialog(null, "Enter a new competition name",
            "Rename Competition", JOptionPane.PLAIN_MESSAGE, null, null, selected.name);

    if (newName != null) {
        Properties props = new Properties();
        props.setProperty("UUID", "" + selected.id);
        props.setProperty("name", newName);
        props.setProperty("password", "" + selected.passwordHash);
        props.setProperty("version", selected.version);

        File infoFile = new File(selected.localDirectory, "info.dat");

        try {
            props.store(new FileOutputStream(infoFile), null);
        } catch (IOException e) {
            log.error("Unable to write database info to file", e);
        }
        checkDatabasesExecutor.schedule(checkDatabasesTask, 0, TimeUnit.MILLISECONDS);
    }
}

From source file:org.schedulesdirect.grabber.Grabber.java

/**
 * Execute the grabber app//from w  w  w  . j av a2  s.c o  m
 * @param args The command line args
 * @throws IOException Thrown on any unexpected IO error
 * @throws InvalidCredentialsException Thrown if the login attempt to Schedules Direct failed
 * @return {@link GrabberReturnCodes#OK OK} on success, one of the other constants in the interface otherwise; typically one would return this value back to the OS level caller
 * @see GrabberReturnCodes
 */
public int execute(String[] args) throws IOException, InvalidCredentialsException {
    if (!parseArgs(args))
        return ARGS_PARSE_ERR;
    else if (parser.getParsedCommand() == null) {
        parser.usage();
        return NO_CMD_ERR;
    }
    NetworkEpgClient clnt = null;
    try {
        if (!parser.getParsedCommand().equals("audit")) {
            try {
                clnt = new NetworkEpgClient(globalOpts.getUsername(), globalOpts.getPassword(),
                        globalOpts.getUserAgent(), globalOpts.getUrl().toString(), true, factory);
                LOG.debug(String.format("Client details: %s", clnt.getUserAgent()));
            } catch (ServiceOfflineException e) {
                LOG.error("Web service is offline!  Please try again later.");
                return SERVICE_OFFLINE_ERR;
            }
        }
        action = Action.valueOf(parser.getParsedCommand().toUpperCase());
        int rc = CMD_FAILED_ERR;
        switch (action) {
        case LIST:
            if (!listOpts.isHelp()) {
                listLineups(clnt);
                rc = OK;
            } else
                parser.usage(action.toString().toLowerCase());
            break;
        case GRAB:
            if (!grabOpts.isHelp()) {
                updateZip(clnt);
                rc = OK;
            } else
                parser.usage(action.toString().toLowerCase());
            break;
        case ADD:
            if (!addOpts.isHelp())
                addLineup(clnt);
            else
                parser.usage(action.toString().toLowerCase());
            break;
        case DELETE:
            if (!delOpts.isHelp())
                rc = removeHeadend(clnt) ? OK : CMD_FAILED_ERR;
            else
                parser.usage(action.toString().toLowerCase());
            break;
        case INFO:
            if (!infoOpts.isHelp()) {
                dumpAccountInfo(clnt);
                rc = OK;
            } else
                parser.usage(action.toString().toLowerCase());
            break;
        case SEARCH:
            if (!searchOpts.isHelp()) {
                listLineupsForZip(clnt);
                rc = OK;
            } else
                parser.usage(action.toString().toLowerCase());
            break;
        case AUDIT:
            if (!auditOpts.isHelp()) {
                Auditor a = new Auditor(auditOpts);
                a.run();
                if (!a.isFailed())
                    rc = OK;
            } else
                parser.usage(action.toString().toLowerCase());
            break;
        case LISTMSGS:
            if (!listMsgsOpts.isHelp()) {
                listAllMessages(clnt);
                rc = OK;
            } else
                parser.usage(action.toString().toLowerCase());
            break;
        case DELMSG:
            if (!delMsgsOpts.isHelp()) {
                if (deleteMessages(clnt, clnt.getUserStatus().getSystemMessages()) < delMsgsOpts.getIds()
                        .size())
                    deleteMessages(clnt, clnt.getUserStatus().getUserMessages());
                rc = OK;
            } else
                parser.usage(action.toString().toLowerCase());
            break;
        case AVAILABLE:
            if (!availOpts.isHelp()) {
                String type = availOpts.getType();
                if (type == null)
                    listAvailableThings(clnt);
                else
                    listAvailableThings(clnt, type); // TODO: change
                rc = OK;
            } else
                parser.usage(action.toString().toLowerCase());
            break;
        }
        return rc;
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        parser.usage();
        return ARGS_PARSE_ERR;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (clnt != null)
            clnt.close();
        if (grabOpts.getTarget().exists() && action == Action.GRAB) {
            FileSystem target;
            try {
                target = FileSystems.newFileSystem(
                        new URI(String.format("jar:%s", grabOpts.getTarget().toURI())),
                        Collections.<String, Object>emptyMap());
            } catch (URISyntaxException e1) {
                throw new RuntimeException(e1);
            }
            if (action == Action.GRAB && !grabOpts.isHelp() && grabOpts.isPurge() && !freshZip) {
                LOG.warn("Performing a cache cleanup, this will take a few minutes!");
                try {
                    removeExpiredSchedules(target);
                } catch (JSONException e) {
                    throw new IOException(e);
                }
                removeUnusedPrograms(target);
            }
            target.close();
            if (action == Action.GRAB && !grabOpts.isHelp())
                LOG.info(String.format("Created '%s' successfully! [%dms]", target,
                        System.currentTimeMillis() - start));
        }
        if (globalOpts.isSaveCreds()) {
            String user = globalOpts.getUsername();
            String pwd = globalOpts.getPassword();
            if (user != null && user.length() > 0 && pwd != null && pwd.length() > 0) {
                Properties props = new Properties();
                props.setProperty("user", globalOpts.getUsername());
                props.setProperty("password", globalOpts.getPassword());
                Writer w = new FileWriter(OPTS_FILE);
                props.store(w, "Generated by sdjson-grabber");
                w.close();
                LOG.info(String.format("Credentials saved for future use in %s!", OPTS_FILE.getAbsoluteFile()));
            }
        }
    }
}

From source file:jeplus.data.ParameterItem.java

public String toText() {
    Properties prop = new Properties();
    prop.setProperty("ID", ID);
    prop.setProperty("Name", Name);
    prop.setProperty("Type", Integer.toString(Type));
    prop.setProperty("Description", Description);
    prop.setProperty("SearchString", SearchString);
    prop.setProperty("ValuesString", ValuesString);
    StringWriter sw = new StringWriter();
    try {//from  w w w .  j a  v a  2s  .c  o  m
        prop.store(sw, "Parameter item details");
    } catch (Exception ex) {
        logger.error("", ex);
        return null;
    }
    return sw.getBuffer().toString();
}

From source file:com.itemanalysis.jmetrik.workspace.JmetrikPreferencesManager.java

public void loadLog() {
    String logHome = p.get(LOG_HOME, DEFAULT_LOG_HOME);

    //Delete old log properties file -- needed for version 4
    String fullPropertiesName = (logHome + "/" + DEFAULT_LOG_PROPERTY_FILE);
    File f1 = new File(fullPropertiesName);
    if (f1.exists()) {
        f1.delete();//from   w  w  w. j  ava2s  .  c  o  m
        System.out.print("LOG PROP FILE: " + f1.getAbsolutePath() + " DELETED");
    }

    String header = "#DO NOT EDIT - JMETRIK LOG PROPERTIES FILE - DO NOT EDIT";
    fullPropertiesName = (logHome + "/" + DEFAULT_LOG_PROPERTY_FILE_V4);
    String fullLogFileName = (logHome + "/" + DEFAULT_LOG_NAME);
    String fullScriptLogFileName = (logHome + "/" + DEFAULT_SCRIPT_LOG_NAME);

    //create log properties file, if it does not exist
    createLogProperties(logHome);

    //start logging
    Properties p = new Properties();
    File f = new File(fullPropertiesName);
    try {
        File logFile = new File(logHome + "/" + DEFAULT_LOG_NAME);
        if (!logFile.exists())
            logFile.createNewFile();

        FileInputStream in = new FileInputStream(f);
        p.load(in);
        in.close();
        p.setProperty("log4j.appender.jmetrik-logger.File", fullLogFileName);
        p.setProperty("log4j.appender.jmetrik-script-logger.File", fullScriptLogFileName);

        FileOutputStream out = new FileOutputStream(new File(fullLogFileName));
        p.store(out, header);
        out.close();
        PropertyConfigurator.configure(p);
        logger.info("Logging started");
    } catch (IOException ex) {
        this.firePropertyChange("error", "", "Error - Unable to configure log.");
    }

}

From source file:com.streamsets.datacollector.cluster.TestShellClusterProvider.java

@Test
public void testCopyDpmToken() throws Exception {
    Properties sdcProperties = new Properties();
    sdcProperties.put(Configuration.CONFIG_INCLUDES, "dpm-test.properties");
    File etcDir = tempFolder.newFolder();
    Properties dpmProperties = new Properties();
    dpmProperties.setProperty("foo", "fooVal");
    dpmProperties.setProperty(RemoteSSOService.DPM_ENABLED, "true");
    File appTokenFile = tempFolder.newFile();
    try (PrintWriter out = new PrintWriter(appTokenFile)) {
        out.println("app-token-dummy-text");
    }//  w ww.j  a  v  a 2s .co  m
    // dpm enabled and app token is absolute
    dpmProperties.setProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG,
            Configuration.FileRef.DELIMITER + appTokenFile.getAbsolutePath() + Configuration.FileRef.DELIMITER);

    try (OutputStream out = new FileOutputStream(new File(etcDir, "dpm-test.properties"))) {
        dpmProperties.store(out, null);
    }
    sparkProvider.copyDpmTokenIfRequired(sdcProperties, etcDir);
    try (InputStream in = new FileInputStream(new File(etcDir, "dpm-test.properties"))) {
        Properties gotProperties = new Properties();
        gotProperties.load(in);
        Assert.assertEquals("fooVal", gotProperties.getProperty("foo"));
        Assert.assertEquals("true", gotProperties.getProperty(RemoteSSOService.DPM_ENABLED));
        Assert.assertEquals(
                Configuration.FileRef.DELIMITER + ShellClusterProvider.CLUSTER_DPM_APP_TOKEN
                        + Configuration.FileRef.DELIMITER,
                gotProperties.getProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG));
        List<String> gotLines = Files.readAllLines(
                new File(etcDir, ShellClusterProvider.CLUSTER_DPM_APP_TOKEN).toPath(),
                Charset.defaultCharset());
        Assert.assertEquals(1, gotLines.size());
        Assert.assertEquals("app-token-dummy-text", gotLines.get(0));
    }
    // dpm not enabled
    etcDir = tempFolder.newFolder();
    dpmProperties = new Properties();
    dpmProperties.setProperty("foo", "fooNewVal");
    dpmProperties.setProperty(RemoteSSOService.DPM_ENABLED, "false");
    try (OutputStream out = new FileOutputStream(new File(etcDir, "dpm-test.properties"))) {
        dpmProperties.store(out, null);
    }
    sparkProvider.copyDpmTokenIfRequired(sdcProperties, etcDir);
    try (InputStream in = new FileInputStream(new File(etcDir, "dpm-test.properties"))) {
        Properties gotProperties = new Properties();
        gotProperties.load(in);
        Assert.assertEquals("fooNewVal", gotProperties.getProperty("foo"));
        Assert.assertEquals("false", gotProperties.getProperty(RemoteSSOService.DPM_ENABLED));
    }
    // dpm enabled but token relative
    etcDir = tempFolder.newFolder();
    dpmProperties = new Properties();
    dpmProperties.setProperty("foo", "fooDpmEnabledTokenRelative");
    dpmProperties.setProperty(RemoteSSOService.DPM_ENABLED, "true");
    dpmProperties.setProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG,
            Configuration.FileRef.DELIMITER + "relative_path_to_token.txt" + Configuration.FileRef.DELIMITER);
    try (OutputStream out = new FileOutputStream(new File(etcDir, "dpm-test.properties"))) {
        dpmProperties.store(out, null);
    }
    sparkProvider.copyDpmTokenIfRequired(sdcProperties, etcDir);
    try (InputStream in = new FileInputStream(new File(etcDir, "dpm-test.properties"))) {
        Properties gotProperties = new Properties();
        gotProperties.load(in);
        Assert.assertEquals("fooDpmEnabledTokenRelative", gotProperties.getProperty("foo"));
        Assert.assertEquals("true", gotProperties.getProperty(RemoteSSOService.DPM_ENABLED));
        Assert.assertEquals(
                Configuration.FileRef.DELIMITER + "relative_path_to_token.txt"
                        + Configuration.FileRef.DELIMITER,
                gotProperties.getProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG));
    }
    // all configs in sdc.properties (similar to parcels)
    sdcProperties.remove(Configuration.CONFIG_INCLUDES);
    sdcProperties.setProperty(RemoteSSOService.DPM_ENABLED, "true");
    sdcProperties.setProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG,
            Configuration.FileRef.DELIMITER + appTokenFile.getAbsolutePath() + Configuration.FileRef.DELIMITER);
    sparkProvider.copyDpmTokenIfRequired(sdcProperties, etcDir);
    Assert.assertEquals("true", sdcProperties.getProperty(RemoteSSOService.DPM_ENABLED));
    Assert.assertEquals(
            Configuration.FileRef.DELIMITER + ShellClusterProvider.CLUSTER_DPM_APP_TOKEN
                    + Configuration.FileRef.DELIMITER,
            sdcProperties.getProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG));
}

From source file:iristk.util.Record.java

/**
 * Saves the record in a properties file. If the file already exists, the content in the file is overwritten with the new record data.
 * /*from  w ww  .  j a va2  s  .  c  o  m*/
 * @param file The file the record data are stored in
 * @throws IOException
 */
public void toProperties(File file) throws IOException {
    Properties prop = toProperties();
    //Without the if the method will throw a NullPointer when no parent is directly specified when creating the new file
    if (file.getParent() != null) {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
    }
    OutputStream out = new FileOutputStream(file);
    prop.store(out, "");
    out.close();

}

From source file:com.googlecode.fascinator.transformer.jsonVelocity.JsonVelocityTransformer.java

private boolean okToProcess(DigitalObject in, JsonSimple itemConfig) throws TransformerException {
    if (itemConfig.getBoolean(false, "checkForTFMETAProperty")) {
        String propertyName = itemConfig.getString(null, "TFMETAPropertyName");
        String propertyValue = itemConfig.getString(null, "TFMETAPropertyValue");
        if (propertyName != null && propertyValue != null) {
            Properties tfMetadata;
            try {
                tfMetadata = in.getMetadata();
            } catch (StorageException e) {
                throw new TransformerException(e);
            }//from  w  w  w.  ja  v  a 2s . c  om
            if (!propertyValue.equals(tfMetadata.getProperty(propertyName))) {
                return false;
            }
            if (itemConfig.getBoolean(false, "clearPropertyOnTransform")) {
                ByteArrayInputStream input;
                try {
                    tfMetadata.remove(propertyName);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    tfMetadata.store(output, null);
                    input = new ByteArrayInputStream(output.toByteArray());
                    StorageUtils.createOrUpdatePayload(in, "TF-OBJ-META", input);
                } catch (Exception e) {
                    throw new TransformerException(e);
                }

            }
        }

    }
    return true;
}

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

/**
 * Upgrade from version 1.1 to 1.2//from  w  w w  .ja v a2  s  .c om
 */
@SuppressWarnings("unused")
private void up1100To1200() throws Exception {
    log.info("Version 1.1 to 1.2 is upgarding");

    String root = DataRoot.getDataRoot();
    Server server = new Server();
    Properties prop = FileUtil.loadProperties(root + Server.FILE);
    server.syncFrom(prop);
    server.setDbType("mysql");
    server.setDbConnectType("jndi");
    server.setQuartzJobstoreDriver("org.quartz.impl.jdbcjobstore.StdJDBCDelegate");

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

From source file:fll.scheduler.SchedulerUI.java

void saveScheduleDescription() {
    if (null == mScheduleDescriptionFile) {
        // prompt the user for a filename to save to

        final String startingDirectory = PREFS.get(DESCRIPTION_STARTING_DIRECTORY_PREF, null);

        final JFileChooser fileChooser = new JFileChooser();
        final FileFilter filter = new BasicFileFilter("FLL Schedule Description (properties)",
                new String[] { "properties" });
        fileChooser.setFileFilter(filter);
        if (null != startingDirectory) {
            fileChooser.setCurrentDirectory(new File(startingDirectory));
        }// w ww. j  a va  2  s. com

        final int returnVal = fileChooser.showSaveDialog(SchedulerUI.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            final File currentDirectory = fileChooser.getCurrentDirectory();
            PREFS.put(DESCRIPTION_STARTING_DIRECTORY_PREF, currentDirectory.getAbsolutePath());

            mScheduleDescriptionFile = fileChooser.getSelectedFile();
            mDescriptionFilename.setText(mScheduleDescriptionFile.getName());
        } else {
            // user canceled
            return;
        }
    }

    try (final Writer writer = new OutputStreamWriter(new FileOutputStream(mScheduleDescriptionFile),
            Utilities.DEFAULT_CHARSET)) {
        final SolverParams params = mScheduleDescriptionEditor.getParams();
        final List<String> errors = params.isValid();
        if (!errors.isEmpty()) {
            final String formattedErrors = errors.stream().collect(Collectors.joining("\n"));
            JOptionPane.showMessageDialog(SchedulerUI.this,
                    "There are errors that need to be corrected before the description can be saved: "
                            + formattedErrors,
                    "Error saving file", JOptionPane.ERROR_MESSAGE);
        } else {
            final Properties properties = new Properties();
            params.save(properties);
            properties.store(writer, null);
        }
    } catch (final IOException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error saving file: %s", e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error saving file",
                JOptionPane.ERROR_MESSAGE);
    }
}