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:it.scoppelletti.security.keypairgen.KeyPairGeneratorBean.java

/**
 * Esegue l’operazione.// w  ww  . j a v a  2  s . co  m
 */
public void run() {
    Properties props;
    OutputStream publicOut = null;
    OutputStream privateOut = null;
    KeyPair keyPair;
    KeyPairGenerator keyGen;

    if (myConfigFile == null) {
        throw new PropertyNotSetException(toString(), "configFile");
    }
    if (myPublicFile == null) {
        throw new PropertyNotSetException(toString(), "publicFile");
    }
    if (myPrivateFile == null) {
        throw new PropertyNotSetException(toString(), "privateFile");
    }

    try {
        props = loadConfig();
        publicOut = openOutput(myPublicFile);
        if (publicOut == null) {
            return;
        }
        privateOut = openOutput(myPrivateFile);
        if (privateOut == null) {
            return;
        }

        keyGen = CryptoUtils.getKeyPairGenerator(props, myPrefix);
        keyPair = keyGen.generateKeyPair();

        props = CryptoUtils.toProperties(keyPair.getPublic(), myEncoded);
        props.store(publicOut, null);

        props = CryptoUtils.toProperties(keyPair.getPrivate(), myEncoded);
        props.store(privateOut, null);
    } catch (IOException ex) {
        throw new IOOperationException(ex);
    } finally {
        if (publicOut != null) {
            IOUtils.close(publicOut);
            publicOut = null;
        }
        if (privateOut != null) {
            IOUtils.close(privateOut);
            privateOut = null;
        }
    }
}

From source file:com.twinsoft.convertigo.eclipse.ConvertigoPlugin.java

static public String makeAnonymousPsc() throws IOException {
    Properties properties = new Properties();
    String anonEmail = Long.toString(System.currentTimeMillis(), Character.MAX_RADIX)
            + Long.toString(Math.round(Math.random()) % Character.MAX_RADIX, Character.MAX_RADIX)
            + "@anonym.ous";

    DeploymentKey.adminUser.setValue(properties, 1, anonEmail);
    DeploymentKey.adminPassword.setValue(properties, 1, "");
    DeploymentKey.server.setValue(properties, 1, "");

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    properties.store(os, " PSC file");
    String psc = new String(os.toByteArray(), "iso8859-1");
    psc = Crypto2.encodeToHexString("registration", psc);

    return psc;/*  w w  w  .ja  v a  2s .c om*/
}

From source file:org.cloudifysource.restclient.GSRestClient.java

/**
 * Writes the given properties to a temporary text files and returns it. The text file will be deleted
 * automatically.// w  w w  .  j  a  va  2  s.c  o  m
 *
 * @param props
 *            Properties to write to a temporary text (.tmp) file
 * @return File object - the properties file created.
 * @throws IOException
 *             Reporting failure to create the text file.
 */
protected final File writeMapToFile(final Properties props) throws IOException {

    // then dump properties into file
    File tempFile = null;
    FileWriter writer = null;
    try {
        tempFile = File.createTempFile("uploadTemp", ".tmp");
        tempFile.deleteOnExit();
        writer = new FileWriter(tempFile, true);
        if (props != null) {
            props.store(writer, "");
        }

    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (final IOException e) {
                // ignore
            }
        }
    }

    return tempFile;
}

From source file:net.sourceforge.buildmonitor.monitors.BambooProperties.java

/**
 * Save the properties from the {@link #USER_PROPERTIES_FILE} file in the
 * user home directory./*from   w  ww. j  a v a2s .co m*/
 */
public void saveToFile() throws FileNotFoundException, IOException {
    // Build a Properties object that contains the values of the bamboo properties
    Properties bambooMonitorProperties = new Properties();
    synchronized (this) {
        String proppassword = "{base64}" + new String(Base64.encodeBase64(getPassword().getBytes()));
        bambooMonitorProperties.setProperty(BAMBOO_SERVER_BASE_URL_PROPERTY_KEY, getServerBaseUrl());
        bambooMonitorProperties.setProperty(BAMBOO_USERNAME_PROPERTY_KEY, getUsername());
        bambooMonitorProperties.setProperty(BAMBOO_PASSWORD_PROPERTY_KEY, proppassword);
        bambooMonitorProperties.setProperty(BAMBOO_FAVOURITE_PROJECTS_ONLY, "" + getFavouriteProjectsOnly());
        bambooMonitorProperties.setProperty(UPDATE_PERIOD_IN_SECONDS_PROPERTY_KEY,
                "" + getUpdatePeriodInSeconds());
    }

    // Store the Properties object in the file
    File bambooMonitorPropertiesFile = new File(System.getProperty("user.home"), USER_PROPERTIES_FILE);
    FileOutputStream buildMonitorPropertiesOutputStream = new FileOutputStream(bambooMonitorPropertiesFile);
    bambooMonitorProperties.store(buildMonitorPropertiesOutputStream, "File last updated on " + new Date());
    buildMonitorPropertiesOutputStream.close();
}

From source file:dk.itst.oiosaml.sp.IntegrationTests.java

@Before
public final void setUpServer() throws Exception {
    tmpdir = new File(System.getProperty("java.io.tmpdir") + "/oiosaml-" + Math.random());
    tmpdir.mkdir();/*from   ww w .j a v a  2s .com*/
    FileUtils.forceMkdir(new File(tmpdir, "metadata/IdP"));
    FileUtils.forceMkdir(new File(tmpdir, "metadata/SP"));

    credential = TestHelper.getCredential();
    EntityDescriptor idpDescriptor = TestHelper.buildEntityDescriptor(credential);
    FileOutputStream fos = new FileOutputStream(new File(tmpdir, "metadata/IdP/gen.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(idpDescriptor)).getBytes(), fos);
    fos.close();

    EntityDescriptor spDescriptor = (EntityDescriptor) SAMLUtil
            .unmarshallElement(getClass().getResourceAsStream("/dk/itst/oiosaml/sp/SPMetadata.xml"));
    fos = new FileOutputStream(new File(tmpdir, "metadata/SP/SPMetadata.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(spDescriptor)).getBytes(), fos);
    fos.close();

    spMetadata = new SPMetadata(spDescriptor, SAMLConstants.SAML20P_NS);
    idpMetadata = new IdpMetadata(SAMLConstants.SAML20P_NS, idpDescriptor);

    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.log4j.xml"));
    IOUtils.write(
            "<!DOCTYPE log4j:configuration SYSTEM \"http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd\"><log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"false\"></log4j:configuration>",
            fos);
    fos.close();

    Properties props = new Properties();
    props.setProperty(Constants.PROP_CERTIFICATE_LOCATION, "keystore");
    props.setProperty(Constants.PROP_CERTIFICATE_PASSWORD, "password");
    props.setProperty(Constants.PROP_LOG_FILE_NAME, "oiosaml-sp.log4j.xml");
    props.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    props.setProperty(Constants.PROP_SESSION_HANDLER_FACTORY, SingleVMSessionHandlerFactory.class.getName());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setKeyEntry("oiosaml", credential.getPrivateKey(), "password".toCharArray(),
            new Certificate[] { TestHelper.getCertificate(credential) });
    OutputStream bos = new FileOutputStream(new File(tmpdir, "keystore"));
    ks.store(bos, "password".toCharArray());
    bos.close();

    props.setProperty(Constants.PROP_ASSURANCE_LEVEL, "2");
    props.setProperty(Constants.PROP_IGNORE_CERTPATH, "true");
    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.properties"));
    props.store(fos, "Generated");
    fos.close();

    SAMLConfiguration.setSystemConfiguration(null);
    IdpMetadata.setMetadata(null);
    SPMetadata.setMetadata(null);
    System.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    server = new Server(8808);
    WebAppContext wac = new WebAppContext();
    wac.setClassLoader(Thread.currentThread().getContextClassLoader());
    wac.setContextPath("/saml");
    wac.setWar("webapp/");

    server.setHandler(wac);
    server.start();

    client = new WebClient();
    client.setRedirectEnabled(false);
    client.setThrowExceptionOnFailingStatusCode(false);
    handler = new RedirectRefreshHandler();
    client.setRefreshHandler(handler);
}

From source file:com.hp.application.automation.tools.run.RunFromFileBuilder.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) {

    EnvVars env = null;/*ww w  .  ja v  a  2 s .c  o  m*/
    try {
        env = build.getEnvironment(listener);

    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (InterruptedException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    VariableResolver<String> varResolver = build.getBuildVariableResolver();

    // now merge them into one list
    Properties mergedProperties = new Properties();

    mergedProperties.putAll(runFromFileModel.getProperties(env, varResolver));
    int idx = 0;
    for (String key : env.keySet()) {
        idx++;
        mergedProperties.put("JenkinsEnv" + idx, key + ";" + env.get(key));
    }

    Date now = new Date();
    Format formatter = new SimpleDateFormat("ddMMyyyyHHmmssSSS");
    String time = formatter.format(now);

    // get a unique filename for the params file
    ParamFileName = "props" + time + ".txt";
    ResultFilename = "Results" + time + ".xml";
    //KillFileName = "stop" + time + ".txt";

    mergedProperties.put("runType", RunType.FileSystem.toString());
    mergedProperties.put("resultsFilename", ResultFilename);

    // get properties serialized into a stream
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        mergedProperties.store(stream, "");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        build.setResult(Result.FAILURE);
    }
    String propsSerialization = stream.toString();
    InputStream propsStream = IOUtils.toInputStream(propsSerialization);

    // get the remote workspace filesys
    FilePath projectWS = build.getWorkspace();

    // Get the URL to the Script used to run the test, which is bundled
    // in the plugin
    URL cmdExeUrl = Hudson.getInstance().pluginManager.uberClassLoader.getResource(HpToolsLauncher_SCRIPT_NAME);
    if (cmdExeUrl == null) {
        listener.fatalError(HpToolsLauncher_SCRIPT_NAME + " not found in resources");
        return false;
    }

    URL cmdExe2Url = Hudson.getInstance().pluginManager.uberClassLoader.getResource(LRAnalysisLauncher_EXE);
    if (cmdExe2Url == null) {
        listener.fatalError(LRAnalysisLauncher_EXE + "not found in resources");
        return false;
    }

    FilePath propsFileName = projectWS.child(ParamFileName);
    FilePath CmdLineExe = projectWS.child(HpToolsLauncher_SCRIPT_NAME);
    FilePath CmdLineExe2 = projectWS.child(LRAnalysisLauncher_EXE);

    try {
        // create a file for the properties file, and save the properties
        propsFileName.copyFrom(propsStream);

        // Copy the script to the project workspace
        CmdLineExe.copyFrom(cmdExeUrl);

        CmdLineExe2.copyFrom(cmdExe2Url);

    } catch (IOException e1) {
        build.setResult(Result.FAILURE);
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (InterruptedException e1) {
        build.setResult(Result.FAILURE);
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        // Run the HpToolsLauncher.exe
        AlmToolsUtils.runOnBuildEnv(build, launcher, listener, CmdLineExe, ParamFileName);
        // Has the report been successfuly generated?
    } catch (IOException ioe) {
        Util.displayIOException(ioe, listener);
        build.setResult(Result.FAILURE);
        return false;
    } catch (InterruptedException e) {
        build.setResult(Result.ABORTED);
        PrintStream out = listener.getLogger();

        try {
            AlmToolsUtils.runHpToolsAborterOnBuildEnv(build, launcher, listener, ParamFileName);
        } catch (IOException e1) {
            Util.displayIOException(e1, listener);
            build.setResult(Result.FAILURE);
            return false;
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // kill processes
        /*FilePath killFile = projectWS.child(KillFileName);
        try {
           killFile.write("\n", "UTF-8");
        while (!killFile.exists())
            Thread.sleep(1000);
        Thread.sleep(1500);
        } catch (IOException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        } catch (InterruptedException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        }*/

        out.println("Operation Was aborted by user.");
    }

    return true;

}

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilder.java

File writeProperties(File packageFolder, int articleCount) throws IOException, FileNotFoundException {
    File propertiesFile = new File(packageFolder, IMPORT_PROPERTIES_FILENAME);
    Properties properties = new Properties();
    gcalendar.setTimeInMillis(System.currentTimeMillis());
    String importDate = DatatypeConverter.printDateTime(gcalendar);
    properties.setProperty(PROP_IMPORT_INFODATE, importDate);
    properties.setProperty(PROP_IMPORT_OBJECTS, String.valueOf(articleCount));
    properties.setProperty(PROP_IMPORT_CONTENT_FILES, "0");
    properties.setProperty(PROP_IMPORT_BWMETA_FILES, "1");
    Writer propsWriter = new NoCommentsWriter(
            new OutputStreamWriter(new FileOutputStream(propertiesFile), Charsets.UTF_8));
    try {/*from   w w  w.ja  va 2 s.c  o  m*/
        properties.store(propsWriter, null);
        return propertiesFile;
    } finally {
        propsWriter.close();
    }
}

From source file:com.android.sdklib.internal.repository.Archive.java

/**
 * Generates a source.properties in the destination folder that contains all the infos
 * relevant to this archive, this package and the source so that we can reload them
 * locally later.//from w w w.j av  a2 s.c  o  m
 */
private boolean generateSourceProperties(File unzipDestFolder) {
    Properties props = new Properties();

    saveProperties(props);
    mPackage.saveProperties(props);

    FileOutputStream fos = null;
    try {
        File f = new File(unzipDestFolder, SdkConstants.FN_SOURCE_PROP);

        fos = new FileOutputStream(f);

        props.store(fos, "## Android Tool: Source of this archive."); //$NON-NLS-1$

        return true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
    }

    return false;
}

From source file:org.ala.spatial.web.services.GDMWSController.java

@RequestMapping(value = "/step1", method = RequestMethod.POST)
public @ResponseBody String processStep1(HttpServletRequest req) {

    try {/*  www  .j a  v a  2 s.c o  m*/

        String outputdir = "";
        long currTime = System.currentTimeMillis();

        String envlist = req.getParameter("envlist");
        //String speciesdata = req.getParameter("speciesdata");
        String area = req.getParameter("area");
        String taxacount = req.getParameter("taxacount");

        String bs = req.getParameter("bs");
        String speciesq = req.getParameter("speciesq");

        OccurrenceData od = new OccurrenceData();
        String[] s = od.getSpeciesData(speciesq, bs, null);

        String speciesdata = s[0];

        //Layer[] layers = getEnvFilesAsLayers(envlist);

        LayerFilter[] filter = null;
        SimpleRegion region = null;
        if (area != null && area.startsWith("ENVELOPE")) {
            filter = LayerFilter.parseLayerFilters(area);
        } else {
            region = SimpleShapeFile.parseWKT(area);
        }

        // 1. create work/output directory
        //outputdir = TabulationSettings.base_output_dir + currTime + "/";
        outputdir = AlaspatialProperties.getBaseOutputDir() + "output" + File.separator + "gdm" + File.separator
                + currTime + File.separator;
        File outdir = new File(outputdir);
        outdir.mkdirs();

        System.out.println("gdm.outputpath: " + outputdir);

        // 2. generate species file
        //String speciesFile = generateSpeciesFile(outputdir, taxons, region);
        String speciesFile = generateSpeciesFile(outputdir, speciesdata);

        System.out.println("gdm.speciesFile: " + speciesFile);

        // 3. cut environmental layers
        //String cutDataPath = GridCutter.cut(layers, region, filter, null);
        //SpatialSettings ssets = new SpatialSettings();
        //String cutDataPath = ssets.getEnvDataPath();

        String resolution = req.getParameter("res");
        if (resolution == null) {
            resolution = "0.01";
        }
        String cutDataPath = GridCutter.cut2(envlist.split(":"), resolution, region, filter, null);

        System.out.println("CUTDATAPATH: " + region + " " + cutDataPath);

        System.out.println("gdm.cutDataPath: " + cutDataPath);

        // 4. produce domain grid
        //DomainGrid.generate(cutDataPath, layers, region, outputdir);

        // 5. build parameters files for GDM
        String params = generateStep1Paramfile(envlist.split(":"), cutDataPath, speciesFile, outputdir);

        // 6. run GDM
        int exit = runGDM(1, params);
        System.out.println("gdm.exit: " + exit);

        String output = "";
        output += Long.toString(currTime) + "\n";
        //            BufferedReader cutpoint = new BufferedReader(new FileReader(outputdir + "Cutpoint.csv"));
        //            String line = "";
        //            while ((line = cutpoint.readLine()) != null) {
        //                output += line;
        //            }
        Scanner sc = new Scanner(new File(outputdir + "Cutpoint.csv"));
        while (sc.hasNextLine()) {
            output += sc.nextLine() + "\n";
        }

        // write the properties to a file so we can grab them back later
        Properties props = new Properties();
        props.setProperty("pid", Long.toString(currTime));
        props.setProperty("envlist", envlist);
        props.setProperty("area", area);
        props.setProperty("taxacount", taxacount);
        //props.store(new PrintWriter(new BufferedWriter(new FileWriter(outputdir + "ala.properties"))), "");
        props.store(new FileOutputStream(outputdir + "ala.properties"), "ALA GDM Properties");

        return output;

    } catch (Exception e) {
        System.out.println("Error processing gdm request");
        e.printStackTrace(System.out);
    }

    return "";
}

From source file:edu.kit.dama.dataworkflow.AbstractExecutionEnvironmentHandler.java

/**
 * Prepare the user application of the provided task. The preparation
 * includes obtaining the application archive from the application archive
 * URL that is part of the task configuration, extract the obtained ZIP
 * archive to the working directory of the task and finally, perform
 * variable substitution.//  w w  w.  ja v  a2  s .  c  o m
 *
 * Due to the fact, that the working directory of the task is accessible
 * from the repository system running locally as well as from the execution
 * environment potentially located somewhere else, the entire preparation
 * can be identical for almost any imaginable
 * EnvironmentHandler-implementation. Therefor, this method is not abstract
 * but implemented in a default way and can be overwritten if required.
 *
 * @param pTask The task for which the application should be prepared.
 *
 * @throws ExecutionPreparationException If one part of the preparation
 * fails.
 */
private void prepareApplication(DataWorkflowTask pTask) throws ExecutionPreparationException {
    //obtain and extract zip
    File executionBasePath;
    try {
        executionBasePath = DataWorkflowHelper.getStagingBasePath(pTask);
    } catch (IOException ex) {
        throw new ExecutionPreparationException("Failed to prepare execution.", ex);
    }
    File workingDirectory = DataWorkflowHelper.getTaskWorkingDirectory(executionBasePath);
    File destination = new File(workingDirectory, "userApplication.zip");
    FileOutputStream propertiesStream = null;
    try {
        LOGGER.debug("Obtaining application package URL");
        AbstractFile applicationPackage = new AbstractFile(
                new URL(pTask.getConfiguration().getApplicationPackageUrl()));
        LOGGER.debug("Downloading application archive from {} to {}", applicationPackage, destination);
        applicationPackage.downloadFileToFile(new AbstractFile(destination));
        LOGGER.debug("User application archive successfully downloaded. Extracting user application to {}",
                destination.getParentFile());
        ZipUtils.unzip(destination, destination.getParentFile());
        LOGGER.debug("Deleting user application archive. Success: {}", destination.delete());
        LOGGER.debug("User application successfully extracted. Performing variable substition.");
        DataWorkflowHelper.substituteVariablesInDirectory(pTask);
        LOGGER.debug("Variable substitution finished. Storing custom properties.");
        Properties settings = pTask.getExecutionSettingsAsObject();
        if (settings != null) {
            propertiesStream = new FileOutputStream(new File(workingDirectory, "dataworkflow.properties"));
            settings.store(propertiesStream, null);
        }
        LOGGER.debug("Custom properties stored. User application successfully prepared.");
    } catch (MalformedURLException | AdalapiException ex) {
        throw new ExecutionPreparationException("Failed to obtain user application package.", ex);
    } catch (IOException | URISyntaxException ex) {
        throw new ExecutionPreparationException(
                "Failed to extract user application package or failed to substitute DataWorkflow variables.",
                ex);
    } finally {
        if (propertiesStream != null) {
            try {
                propertiesStream.close();
            } catch (IOException ex) {
                //ignore this
            }
        }
    }
}