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:com.dtolabs.rundeck.core.common.impl.URLFileUpdater.java

/**
 * Cache etag and last-modified header info for a response
 *//*w w  w. ja v  a 2  s  .  c om*/
private void cacheResponseInfo(final httpClientInteraction method, final File cacheFile) {
    //write cache data to file if present
    Properties newprops = new Properties();

    if (null != method.getResponseHeader(LAST_MODIFIED)) {
        newprops.setProperty(LAST_MODIFIED, method.getResponseHeader(LAST_MODIFIED).getValue());
    }
    if (null != method.getResponseHeader(E_TAG)) {
        newprops.setProperty(E_TAG, method.getResponseHeader(E_TAG).getValue());
    }
    if (null != method.getResponseHeader(CONTENT_TYPE)) {
        newprops.setProperty(CONTENT_TYPE, method.getResponseHeader(CONTENT_TYPE).getValue());
    }
    if (newprops.size() > 0) {
        try {
            final FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
            try {
                newprops.store(fileOutputStream, "URLFileUpdater cache data for URL: " + url);
            } finally {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            logger.debug("Failed to write cache header info to file: " + cacheFile + ", " + e.getMessage(), e);
        }
    } else if (cacheFile.exists()) {
        if (!cacheFile.delete()) {
            logger.warn("Unable to delete cachefile: " + cacheFile.getAbsolutePath());
        }
    }
}

From source file:org.netxilia.api.impl.storage.DataSourceConfigurationServiceImpl.java

@Override
public synchronized DataSourceConfiguration save(DataSourceConfiguration cfg) throws StorageException {
    init();//from   www  . j a v a 2  s  . c o m
    DataSourceConfiguration returnCfg = cfg;

    if (cfg.getId() == null) {
        DataSourceConfigurationId newId = newId();
        returnCfg = new DataSourceConfiguration(newId, cfg.getName(), cfg.getDescription(),
                cfg.getDriverClassName(), cfg.getUrl(), cfg.getUsername(), cfg.getPassword());
    } else {
        notifyModifyConfiguration(cfg.getId());
        Pair<GenericObjectPool, DataSource> poolInfo = pools.get(cfg.getId());
        if (poolInfo != null) {
            try {
                poolInfo.getFirst().close();
            } catch (Exception e) {
                log.error("Cannot close datasource pool:" + e, e);
            }
        }
        pools.remove(cfg.getId());
        buildDataSource(cfg);
    }
    Properties props = new Properties();
    FileWriter writer = null;

    try {
        props.setProperty(PROP_NAME, returnCfg.getName());
        props.setProperty(PROP_DESCRIPTION, returnCfg.getDescription());
        props.setProperty(PROP_DRIVER, returnCfg.getDriverClassName());
        props.setProperty(PROP_URL, returnCfg.getUrl());
        props.setProperty(PROP_USERNAME, returnCfg.getUsername());
        props.setProperty(PROP_PASSWORD, returnCfg.getPassword());

        writer = new FileWriter(fileForId(returnCfg.getId()));
        props.store(writer, "Saved by Netxilia");

    } catch (IOException e) {
        throw new StorageException(e);
    } finally {
        if (writer != null) {
            try {
                writer.flush();
            } catch (Exception e2) {
                throw new StorageException(e2);
            }
            IOUtils.closeQuietly(writer);
        }
    }

    return returnCfg;

}

From source file:de.adorsys.forge.gwt.GWTFacet.java

public void addMessages(Map<String, String> messages) {
    Properties properties = new Properties();
    ResourceFacet resources = project.getFacet(ResourceFacet.class);
    MavenCoreFacet maven = project.getFacet(MavenCoreFacet.class);
    FileResource<?> resource = resources.getResource(getMessagePropertiesPath());
    InputStream is = resource.getResourceInputStream();
    FileOutputStream fileOutputStream = null;
    try {// w w  w.j av a  2s. c o  m
        // prefer the user messages
        properties.putAll(messages);
        properties.load(new InputStreamReader(is, UTF_8));
        is.close();
        fileOutputStream = new FileOutputStream(resource.getUnderlyingResourceObject());
        properties.store(new OutputStreamWriter(fileOutputStream, UTF_8), null);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            is.close();
            fileOutputStream.close();
        } catch (IOException e) {
        }
    }

    maven.executeMaven(Arrays.asList("generate-resources"));

}

From source file:com.jolira.testing.CachingRESTProxy.java

private void cacheResponse(final File queryDir, final HttpURLConnection connection, final InputStream in)
        throws IOException, FileNotFoundException {
    final String contentType = connection.getHeaderField(CONTENT_TYPE);
    final int code = connection.getResponseCode();
    final String defaultContentType = getDefaultContentType(queryDir);
    final Map<String, List<String>> fields = connection.getHeaderFields();
    final Collection<String> cookies = fields.get(SET_COOKIE);
    final boolean simple = code == SC_OK && equalsContentType(defaultContentType, contentType)
            && isEmpty(cookies);
    final File resourceFile = simple ? queryDir : getResourceFile(queryDir);

    copy(in, resourceFile);/*from  w ww .  ja  v  a  2s  . c  o  m*/

    if (simple) {
        return;
    }

    final Properties prps = new Properties();

    if (contentType != null) {
        prps.put(CONTENT_TYPE, contentType);
    }

    if (cookies != null) {
        int idx = 0;

        for (final String cookie : cookies) {
            final String key = getCookieKey(idx++);

            prps.put(key, cookie);
        }
    }

    prps.put(STATUS_PROPERTY, Integer.toString(code));

    final File propertiesFile = getPropertiesFile(queryDir);
    final OutputStream out = new FileOutputStream(propertiesFile);

    try {
        prps.store(out, "gerated by " + CachingRESTProxy.class);
    } finally {
        out.close();
    }
}

From source file:com.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java

@Test
public void testSuccess() throws Exception {
    Properties sdcProps = new Properties();
    sdcProps.setProperty("a", "b");
    sdcProps.setProperty("c", "d");
    sdcProps.setProperty("kerberos.client.keytab", "sdc.keytab");
    sdcProps.setProperty("kerberos.client.enabled", "false");
    sdcProps.setProperty("kerberos.client.principal", "sdc/_HOST@EXAMPLE.COM");
    File sdcFile = new File(RuntimeInfoTestInjector.confDir, "sdc.properties");

    Properties dpmProps = new Properties();
    dpmProps.setProperty("x", "y");
    dpmProps.setProperty("z", "a");
    dpmProps.setProperty("dpm.enabled", "false");
    dpmProps.setProperty("dpm.base.url", "http://localhost:18631");
    File dpmFile = new File(RuntimeInfoTestInjector.confDir, "dpm.properties");

    try (FileWriter fw = new FileWriter(sdcFile)) {
        sdcProps.store(fw, "");
    }/*  w  w w. ja va2 s . c o  m*/

    try (FileWriter fw = new FileWriter(dpmFile)) {
        dpmProps.store(fw, "");
    }

    Response response = null;
    KeyPair keys = generateKeys();
    mockCheckForCredentialsRequiredToTrue();
    System.setProperty(DPM_AGENT_PUBLIC_KEY, Base64.getEncoder().encodeToString(keys.getPublic().getEncoded()));
    String token = "Frenchies and Pandas";
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initSign(keys.getPrivate());
    sig.update(token.getBytes(Charsets.UTF_8));
    List<String> labels = Arrays.asList("deployment-prod-1", "deployment-prod-2");
    CredentialsBeanJson json = new CredentialsBeanJson(token, "streamsets/172.1.1.0@EXAMPLE.COM",
            Base64.getEncoder().encodeToString("testKeytab".getBytes(Charsets.UTF_8)),
            Base64.getEncoder().encodeToString(sig.sign()), "https://dpm.streamsets.com:18631",
            Arrays.asList("deployment-prod-1", "deployment-prod-2"), "deployment1:org");

    try {
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
        CredentialDeploymentResponseJson responseJson = OBJECT_MAPPER
                .readValue((InputStream) response.getEntity(), CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_USED_AND_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

        // Verify sdc.properties
        sdcProps = new Properties();
        try (FileReader fr = new FileReader(sdcFile)) {
            sdcProps.load(fr);
        }
        Assert.assertEquals("b", sdcProps.getProperty("a"));
        Assert.assertEquals("d", sdcProps.getProperty("c"));
        Assert.assertEquals("streamsets/172.1.1.0@EXAMPLE.COM",
                sdcProps.getProperty("kerberos.client.principal"));
        Assert.assertEquals("true", sdcProps.getProperty("kerberos.client.enabled"));
        Assert.assertEquals("sdc.keytab", sdcProps.getProperty("kerberos.client.keytab"));
        byte[] keyTab = Files.toByteArray(new File(RuntimeInfoTestInjector.confDir, "sdc.keytab"));
        Assert.assertEquals("testKeytab", new String(keyTab, Charsets.UTF_8));
        response = target("/v1/definitions").request().get();
        Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

        dpmProps = new Properties();
        try (FileReader fr = new FileReader(dpmFile)) {
            dpmProps.load(fr);
        }
        Assert.assertEquals("y", dpmProps.getProperty("x"));
        Assert.assertEquals("a", dpmProps.getProperty("z"));
        Assert.assertEquals("true", dpmProps.getProperty("dpm.enabled"));
        Assert.assertEquals(
                Configuration.FileRef.PREFIX + "application-token.txt" + Configuration.FileRef.SUFFIX,
                dpmProps.getProperty("dpm.appAuthToken"));
        Assert.assertEquals("https://dpm.streamsets.com:18631", dpmProps.getProperty("dpm.base.url"));

        Assert.assertEquals(StringUtils.join(labels.toArray(), ","),
                dpmProps.getProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS));
        Assert.assertEquals("deployment1:org", dpmProps.getProperty(RemoteSSOService.DPM_DEPLOYMENT_ID));

        File tokenFile = new File(RuntimeInfoTestInjector.confDir, "application-token.txt");
        try (FileInputStream fr = new FileInputStream(tokenFile)) {
            int len = token.length();
            byte[] tokenBytes = new byte[len];
            Assert.assertEquals(len, fr.read(tokenBytes));
            Assert.assertEquals(token, new String(tokenBytes, Charsets.UTF_8));
        }
        //Test redeploying the credentials again
        response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json));
        responseJson = OBJECT_MAPPER.readValue((InputStream) response.getEntity(),
                CredentialDeploymentResponseJson.class);
        Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_NOT_USED_ALREADY_DEPLOYED,
                responseJson.getCredentialDeploymentStatus());

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:com.raddle.tools.ClipboardTransferMain.java

public ClipboardTransferMain() {
    super();// ww  w .  j a  v a  2 s .  co m
    initGUI();
    //// ??
    Properties p = new Properties();
    File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties");
    if (pf.exists()) {
        try {
            p.load(new FileInputStream(pf));
            serverAddrTxt.setText(StringUtils.defaultString(p.getProperty("server.addr")));
            portTxt.setText(StringUtils.defaultString(p.getProperty("local.port")));
            modifyClipChk.setSelected("true".equals(p.getProperty("allow.modify.local.clip")));
            autoChk.setSelected("true".equals(p.getProperty("auto.modify.remote.clip")));
        } catch (Exception e) {
            updateMessage(e.getMessage());
        }
    }
    m.addListener(new ClipboardListener() {

        @Override
        public void contentChanged(Clipboard clipboard) {
            setRemoteClipboard(false);
        }
    });
    m.setEnabled(autoChk.isSelected());
    //
    try {
        pasteImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_paste.png"));
        grayImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_gray.png"));
        sendImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/mail-send.png"));
        BufferedImage taskImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/taskbar.png"));
        setIconImage(taskImage);
        SystemTray systemTray = SystemTray.getSystemTray();
        trayIcon = new TrayIcon(grayImage, "??");
        systemTray.add(trayIcon);
        ////
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {// ???
                    if (ClipboardTransferMain.this.isVisible()) {
                        ClipboardTransferMain.this.setState(ICONIFIED);
                    } else {
                        ClipboardTransferMain.this.setVisible(true);
                        ClipboardTransferMain.this.setState(NORMAL);
                    }
                }
            }
        });
        ////// event 
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowIconified(WindowEvent e) {
                ClipboardTransferMain.this.setVisible(false);
                super.windowIconified(e);
            }

            @Override
            public void windowClosing(WindowEvent e) {
                File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties");
                pf.getParentFile().mkdirs();
                try {
                    Properties op = new Properties();
                    op.setProperty("server.addr", serverAddrTxt.getText());
                    op.setProperty("local.port", portTxt.getText());
                    op.setProperty("allow.modify.local.clip", modifyClipChk.isSelected() + "");
                    op.setProperty("auto.modify.remote.clip", autoChk.isSelected() + "");
                    FileOutputStream os = new FileOutputStream(pf);
                    op.store(os, "clip-trans");
                    os.flush();
                    os.close();
                } catch (Exception e1) {
                }
                shutdown();
                super.windowClosing(e);
            }
        });
    } catch (Exception e) {
        updateMessage(e.getMessage());
    }
    Thread thread = new Thread() {

        @Override
        public void run() {
            while (true) {
                try {
                    String poll = iconQueue.take();
                    if ("send".equals(poll)) {
                        trayIcon.setImage(grayImage);
                    } else if ("paste".equals(poll)) {
                        Thread.sleep(20);
                        trayIcon.setImage(grayImage);
                    }
                } catch (InterruptedException e1) {
                    return;
                }
            }
        }
    };
    thread.setDaemon(true);
    thread.start();
}

From source file:eu.optimis.vc.api.IsoCreator.IsoImageCreation.java

private void storeMetaDataFile(String version, String type) {
    LOGGER.debug("Creating meta.data properties file for folder stucture version=" + version);
    Properties metaDataVersion = new Properties();
    metaDataVersion.setProperty("version", version);
    metaDataVersion.setProperty("type", type);
    File metaDataFile = new File(isoDataDirectory + File.separator + ".metadata");

    LOGGER.debug("Adding meta.data to ISO");
    try {//www  . j a  v a2 s  .co  m
        FileOutputStream fileOutputStream = new FileOutputStream(metaDataFile);
        metaDataVersion.store(fileOutputStream, "VMC ISO data structure version:");
        fileOutputStream.close();
        LOGGER.debug("Writing endpoint complete!");
    } catch (FileNotFoundException e) {
        LOGGER.error(FILE_NOT_FOUND_EXCEPTION + e);
    } catch (IOException e) {
        LOGGER.error(IO_EXCEPTION + e);
    }
}

From source file:org.messic.server.api.APIAlbum.java

/**
 * Add a resource to the temporal folder. This is necessary to do after things like, wizard, or create album, ..
 * //from ww w  .  j  a  va2 s. com
 * @param albumCode {@link String} album code for the resources to upload
 * @param fileName String file name uploaded
 * @param payload byte[] bytes of the track
 * @throws IOException
 * @throws Exception
 */
public void uploadResource(User user, String albumCode, String fileName, byte[] payload) throws IOException {
    MDOUser mdouser = daoUser.getUserByLogin(user.getLogin());
    File basePath = new File(mdouser.calculateTmpPath(daoSettings.getSettings(), albumCode));
    basePath.mkdirs();

    org.messic.server.api.datamodel.File f = new org.messic.server.api.datamodel.File();
    f.setFileName(fileName);
    String secureFileName = f
            .calculateSecureFileName(daoSettings.getSettings().getIllegalCharacterReplacement());
    FileOutputStream fos = new FileOutputStream(
            new File(basePath.getAbsolutePath() + File.separatorChar + secureFileName));
    fos.write(payload);
    fos.close();

    // Now saving the index file, basically to store the original filename associated with the safe file name
    // the original filename is important for the client, because it is the reference name of the resource
    synchronized (indexTmpSemaphore) {
        Properties p = new Properties();
        File findex = new File(basePath.getAbsolutePath() + File.separatorChar + INDEX_TMP_PROPERTIES_FILENAME);
        if (findex.exists()) {
            FileInputStream fisIndex = new FileInputStream(findex);
            p.load(fisIndex);
            fisIndex.close();
        }
        p.setProperty(secureFileName, fileName);
        FileOutputStream fosIndex = new FileOutputStream(findex);
        p.store(fosIndex, "index temp properties of resources for the album");
        fosIndex.flush();
        fosIndex.close();
    }
}

From source file:cz.cas.lib.proarc.common.config.AppConfigurationTest.java

@Test
public void testReadProperty() throws Exception {
    // init proarc.cfg
    final String expectedPropValue = "test-?"; // test UTF-8
    Properties props = new Properties();
    props.put(TEST_PROPERTY_NAME, expectedPropValue);
    createConfigFile(props, proarcCfg);//ww  w  .java  2  s  . c  o  m

    AppConfiguration pconfig = factory.create(new HashMap<String, String>() {
        {
            put(AppConfiguration.PROPERTY_APP_HOME, confHome.toString());
        }
    });

    Configuration config = pconfig.getConfiguration();
    assertEquals(expectedPropValue, config.getString(TEST_PROPERTY_NAME));
    assertEquals(EXPECTED_DEFAULT_VALUE, config.getString(TEST_DEFAULT_PROPERTY_NAME));

    // test reload (like servlet reload)
    final String expectedReloadValue = "reload";
    props.put(TEST_PROPERTY_NAME, expectedReloadValue);
    OutputStreamWriter propsOut = new OutputStreamWriter(new FileOutputStream(proarcCfg), "UTF-8");
    // FileChangedReloadingStrategy waits 5s to reload changes so give it a chance
    Thread.sleep(5000);
    props.store(propsOut, null);
    propsOut.close();
    assertTrue(proarcCfg.exists());

    AppConfiguration pconfigNew = factory.create(new HashMap<String, String>() {
        {
            put(AppConfiguration.PROPERTY_APP_HOME, confHome.toString());
        }
    });

    Configuration configNew = pconfigNew.getConfiguration();
    assertEquals(expectedReloadValue, configNew.getString(TEST_PROPERTY_NAME));
    assertEquals(EXPECTED_DEFAULT_VALUE, configNew.getString(TEST_DEFAULT_PROPERTY_NAME));

    // test FileChangedReloadingStrategy
    assertEquals(expectedReloadValue, config.getString(TEST_PROPERTY_NAME));
    assertEquals(EXPECTED_DEFAULT_VALUE, config.getString(TEST_DEFAULT_PROPERTY_NAME));
}