下面列出了java.util.Properties#store ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void gatherAdminExtras(HashMap<String, String> values) {
Properties props = new Properties();
Set<String> keys = new HashSet<>(values.keySet());
for (String key : keys) {
if (key.startsWith("android.app.extra")) {
continue;
}
props.put(key, values.get(key));
values.remove(key);
}
StringWriter sw = new StringWriter();
try{
props.store(sw, "admin extras bundle");
values.put(DevicePolicyManager.EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE,
sw.toString());
Log.d(TAG, "Admin extras bundle=" + values.get(
DevicePolicyManager.EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE));
} catch (IOException e) {
Log.e(TAG, "Unable to build admin extras bundle");
}
}
/**
* Stores the given properties object in a file named <code>theme-derived.properties</code> within the
* given theme directory
*
* @param themeDirectory directory the properties file should be created in
* @param themeProperties properties that should be written to the properties file
* @throws IOException
*/
public static void storeThemeProperties(String themeDirectory, Properties themeProperties) throws IOException {
File propertiesFile = new File(themeDirectory, ThemeBuilderConstants.THEME_DERIVED_PROPERTIES_FILE);
// need to remove file if already exists so the new properties will be written
if (propertiesFile.exists()) {
FileUtils.forceDelete(propertiesFile);
}
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(propertiesFile);
themeProperties.store(fileWriter, null);
} finally {
if (fileWriter != null) {
fileWriter.close();
}
}
}
@Test
void shouldReturnAgentAutoRegisterPropertiesIfPresent() throws Exception {
Properties properties = new Properties();
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_KEY, "foo");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_RESOURCES, "foo, zoo");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ENVIRONMENTS, "foo, bar");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_HOSTNAME, "agent01.example.com");
properties.store(new FileOutputStream(configFile), "");
AgentAutoRegistrationProperties reader = new AgentAutoRegistrationPropertiesImpl(configFile);
assertThat(reader.agentAutoRegisterKey()).isEqualTo("foo");
assertThat(reader.agentAutoRegisterResources()).isEqualTo("foo, zoo");
assertThat(reader.agentAutoRegisterEnvironments()).isEqualTo("foo, bar");
assertThat(reader.agentAutoRegisterHostname()).isEqualTo("agent01.example.com");
}
@Override
public void store(final String key, final String value) throws IOException {
if (value != null) {
logsnifferProperties.setProperty(key, value);
} else {
logsnifferProperties.remove(key);
}
File file = new File(homeDir.getHomeDir(),
CoreAppConfig.LOGSNIFFER_PROPERTIES_FILE);
LOGGER.info("Saving config value for key '{}' to file: {}", key,
file.getAbsolutePath());
Properties properties = new Properties();
try {
properties.load(new FileInputStream(file));
} catch (IOException e) {
LOGGER.warn(
"Failed to load current properties from file, continue with empty properties: "
+ file.getAbsolutePath(), e);
}
if (value != null) {
properties.setProperty(key, value);
} else {
properties.remove(key);
}
properties.store(new FileOutputStream(file), null);
}
private static boolean writeProperties(Properties prop, File file) {
if (file.exists() && !file.canWrite())
return false;
try {
PrintStream os = new PrintStream(file);
try {
prop.store(os, "properties");
return true;
} finally {
os.close();
}
} catch (Throwable t) {
return false;
}
}
@Override
public void accept(final TomEE.Builder builder) {
final Archive archive = Archive.archive();
final Properties properties = new Properties();
for (final Clazz clazz : classes) {
archive.add(clazz.clazz);
properties.put(clazz.prefix, "new://" + clazz.clazz.getName());
for (final Map.Entry<String, String> entry : clazz.map.entrySet()) {
properties.put(clazz.prefix + "." + entry.getKey(), entry.getValue());
}
}
final PrintString out = new PrintString();
try {
properties.store(out, "Components");
} catch (IOException e) {
throw new IllegalStateException("Cannot create trixie.properties", e);
}
builder.add("lib/components.jar", archive.asJar());
builder.add("conf/trixie.properties", out.toString());
}
/**
* Store configuration from control hub in persistent manner inside data directory. This configuration will be
* loaded on data collector start and will override any configuration from sdc.properties.
*
* This method call is able to remove existing properties if the value is "null". Please note that the removal will
* only happen from the 'override' file. This method does not have the capability to remove configuration directly
* from sdc.properties.
*
* @param runtimeInfo RuntimeInfo instance
* @param newConfigs New set of config properties
* @throws IOException
*/
public static void storeControlHubConfigs(
RuntimeInfo runtimeInfo,
Map<String, String> newConfigs
) throws IOException {
File configFile = new File(runtimeInfo.getDataDir(), SCH_CONF_OVERRIDE);
Properties properties = new Properties();
// Load existing properties from disk if they exists
if(configFile.exists()) {
try (FileReader reader = new FileReader(configFile)) {
properties.load(reader);
}
}
// Propagate updated configuration
for(Map.Entry<String, String> entry : newConfigs.entrySet()) {
if(entry.getValue() == null) {
properties.remove(entry.getKey());
} else {
properties.setProperty(entry.getKey(), entry.getValue());
}
}
// Store the new updated configuration back to disk
try(FileWriter writer = new FileWriter(configFile)) {
properties.store(writer, null);
}
}
public static boolean saveConfig(Context context, String file,
Properties properties) {
try {
File fil = new File(file);
if (!fil.exists())
fil.createNewFile();
FileOutputStream s = new FileOutputStream(fil);
properties.store(s, "");
s.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private boolean copyDpmTokenIfEnabled(Properties props, File etcStagingDir, String include) throws IOException {
Object isDPMEnabled = props.get(RemoteSSOService.DPM_ENABLED);
if (isDPMEnabled != null) {
if (Boolean.parseBoolean(((String) isDPMEnabled).trim())) {
copyDpmTokenIfAbsolute(props, etcStagingDir);
if (include != null) {
try (OutputStream outputStream = new FileOutputStream(new File(etcStagingDir, include))) {
props.store(outputStream, null);
}
}
return true;
}
}
return false;
}
@Before
public void setup() throws Exception {
testDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
Assert.assertTrue(testDir.mkdirs());
Properties properties = new Properties();
properties.setProperty("credentialStore.id.keystore.type", "PKCS12");
properties.setProperty("credentialStore.id.keystore.file", "credentialStore");
properties.setProperty("credentialStore.id.keystore.storePassword", "1234567890A");
try (OutputStream os = new FileOutputStream(new File(testDir, "sdc.properties"))) {
properties.store(os, "");
}
System.setProperty("sdc.conf.dir", testDir.getAbsolutePath());
}
private void saveEndpoint(String eid, Properties props) throws IOException
{
File file = new File(Constants.endpointsPath() + File.separator + eid);
File tempfile = new File(Constants.endpointsPath() + File.separator + eid + ".temp");
OutputStream os = new FileOutputStream(tempfile);
try {
props.store(os, null);
} finally {
os.close();
}
file.delete();
tempfile.renameTo(file);
}
@Test
public void testJson() throws Exception {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().list()
.layer(0, new DenseLayer.Builder().dist(new NormalDistribution(1, 1e-1)).build())
.inputPreProcessor(0, new CnnToFeedForwardPreProcessor()).build();
String json = conf.toJson();
MultiLayerConfiguration from = MultiLayerConfiguration.fromJson(json);
assertEquals(conf.getConf(0), from.getConf(0));
Properties props = new Properties();
props.put("json", json);
String key = props.getProperty("json");
assertEquals(json, key);
File f = testDir.newFile("props");
f.deleteOnExit();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
props.store(bos, "");
bos.flush();
bos.close();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
Properties props2 = new Properties();
props2.load(bis);
bis.close();
assertEquals(props2.getProperty("json"), props.getProperty("json"));
String json2 = props2.getProperty("json");
MultiLayerConfiguration conf3 = MultiLayerConfiguration.fromJson(json2);
assertEquals(conf.getConf(0), conf3.getConf(0));
}
/**
* Set the value associated with name.
*
* @param name The name of the parameter
* @param value Value for the parameter
*/
public void setValue(String name, String value) {
Properties properties = loadProperties();
try (
OutputStream output = new FileOutputStream(file)
) {
properties.setProperty(name, value);
properties.store(output, "");
output.close();
} catch (IOException e) {
logger.warn(String.format("Could not save the keyvalue store, reason:%s", e.getMessage()));
}
}
/**
* Persists the subscription details for future use.
*
* @param context context
* @throws IOException ex
*/
private void persistSubscriptionInfo(final ProcessContext context) throws IOException {
final Properties props = getSubscriptionPropertiesFromContext(context);
try (final OutputStream out = Files.newOutputStream(getSubscriptionPath())) {
props.store(out, null);
}
}
@Test
public void testGetWhiteListAllValues() throws Exception {
File dir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
Assert.assertTrue(dir.mkdirs());
Properties props = new Properties();
props.setProperty(BootstrapMain.SYSTEM_LIBS_WHITE_LIST_KEY, BootstrapMain.ALL_VALUES);
try (OutputStream os = new FileOutputStream(new File(dir, BootstrapMain.WHITE_LIST_FILE))) {
props.store(os, "");
}
Assert.assertNull(BootstrapMain.getWhiteList(dir.getAbsolutePath(), BootstrapMain.SYSTEM_LIBS_WHITE_LIST_KEY));
}
private void saveConfiguration() throws PAPException, IOException {
//
// Create our properties object
//
Properties properties = new Properties() {
private static final long serialVersionUID = 1L;
// For Debugging it is helpful for the file to be in a sorted order,
// any by returning the keys in the natural Alpha order for strings we get close enough.
// TreeSet is sorted, and this just overrides the normal Properties method to get the keys.
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
//
// Iterate our groups
//
List<String> ids = new ArrayList<String>();
for (PDPGroup group : this.groups) {
ids.add(group.getId());
properties.setProperty(group.getId() + ".name", (group.getName() == null ? "" : group.getName()));
properties.setProperty(group.getId() + ".description", (group.getDescription() == null ? "" : group.getDescription()));
//
// Iterate its PDPs
//
List<String> pdps = new ArrayList<String>();
for (PDP pdp : group.getPdps()) {
pdps.add(pdp.getId());
properties.setProperty(pdp.getId() + ".name", (pdp.getName() == null ? "" : pdp.getName()));
properties.setProperty(pdp.getId() + ".description", (pdp.getDescription() == null ? "" : pdp.getDescription()));
}
String pdpList = "";
if (pdps.size() == 1) {
pdpList = pdps.get(0);
} else if (pdps.size() > 1) {
pdpList = Joiner.on(',').skipNulls().join(pdps);
}
if (logger.isDebugEnabled()) {
logger.debug("Group " + group.getId() + " PDPS: " + pdpList);
}
properties.setProperty(group.getId() + ".pdps", pdpList);
}
if (ids.isEmpty()) {
throw new PAPException("Inconsistency - we have NO groups. We should have at least one.");
}
String groupList = "";
if (ids.size() == 1) {
groupList = ids.get(0);
} else if (ids.size() > 1){
groupList = Joiner.on(',').skipNulls().join(ids);
}
logger.info("New Group List: " + groupList);
properties.setProperty(PROP_PAP_GROUPS, groupList);
//
// Get the default group
//
PDPGroup defaultGroup = this.getDefaultGroup();
if (defaultGroup == null) {
throw new PAPException("Invalid state - no default group.");
}
properties.setProperty(PROP_PAP_GROUPS_DEFAULT, defaultGroup.getId());
//
// Now we can save the file
//
Path file = Paths.get(this.repository.toString(), "xacml.properties");
try (OutputStream os = Files.newOutputStream(file)) {
properties.store(os, "");
}
}
@Override
public void store(Properties props, Writer writer, String header) throws IOException {
props.store(writer, header);
}
private void writeFcInfo() {
Properties props = new Properties();
props.setProperty("version", fileVersion);
X11FontManager fm = (X11FontManager) fontManager;
FontConfigManager fcm = fm.getFontConfigManager();
FontConfigInfo fcInfo = fcm.getFontConfigInfo();
props.setProperty("fcversion", Integer.toString(fcInfo.fcVersion));
if (fcInfo.cacheDirs != null) {
for (int i=0;i<fcInfo.cacheDirs.length;i++) {
if (fcInfo.cacheDirs[i] != null) {
props.setProperty("cachedir."+i, fcInfo.cacheDirs[i]);
}
}
}
for (int i=0; i<fcCompFonts.length; i++) {
FcCompFont fci = fcCompFonts[i];
String styleKey = fci.jdkName+"."+fci.style;
props.setProperty(styleKey+".length",
Integer.toString(fci.allFonts.length));
for (int j=0; j<fci.allFonts.length; j++) {
props.setProperty(styleKey+"."+j+".family",
fci.allFonts[j].familyName);
props.setProperty(styleKey+"."+j+".file",
fci.allFonts[j].fontFile);
}
}
try {
/* This writes into a temp file then renames when done.
* Since the rename is an atomic action within the same
* directory no client will ever see a partially written file.
*/
File fcInfoFile = getFcInfoFile();
File dir = fcInfoFile.getParentFile();
dir.mkdirs();
File tempFile = Files.createTempFile(dir.toPath(), "fcinfo", null).toFile();
FileOutputStream fos = new FileOutputStream(tempFile);
props.store(fos,
"JDK Font Configuration Generated File: *Do Not Edit*");
fos.close();
boolean renamed = tempFile.renameTo(fcInfoFile);
if (!renamed && FontUtilities.debugFonts()) {
System.out.println("rename failed");
warning("Failed renaming file to "+ getFcInfoFile());
}
} catch (Exception e) {
if (FontUtilities.debugFonts()) {
warning("IOException writing to "+ getFcInfoFile());
}
}
}
@Override
public void store(Properties props, Writer writer, String header) throws IOException {
props.store(writer, header);
}
private void writeFcInfo() {
Properties props = new Properties();
props.setProperty("version", fileVersion);
X11FontManager fm = (X11FontManager) fontManager;
FontConfigManager fcm = fm.getFontConfigManager();
FontConfigInfo fcInfo = fcm.getFontConfigInfo();
props.setProperty("fcversion", Integer.toString(fcInfo.fcVersion));
if (fcInfo.cacheDirs != null) {
for (int i=0;i<fcInfo.cacheDirs.length;i++) {
if (fcInfo.cacheDirs[i] != null) {
props.setProperty("cachedir."+i, fcInfo.cacheDirs[i]);
}
}
}
for (int i=0; i<fcCompFonts.length; i++) {
FcCompFont fci = fcCompFonts[i];
String styleKey = fci.jdkName+"."+fci.style;
props.setProperty(styleKey+".length",
Integer.toString(fci.allFonts.length));
for (int j=0; j<fci.allFonts.length; j++) {
props.setProperty(styleKey+"."+j+".family",
fci.allFonts[j].familyName);
props.setProperty(styleKey+"."+j+".file",
fci.allFonts[j].fontFile);
}
}
try {
/* This writes into a temp file then renames when done.
* Since the rename is an atomic action within the same
* directory no client will ever see a partially written file.
*/
File fcInfoFile = getFcInfoFile();
File dir = fcInfoFile.getParentFile();
dir.mkdirs();
File tempFile = Files.createTempFile(dir.toPath(), "fcinfo", null).toFile();
FileOutputStream fos = new FileOutputStream(tempFile);
props.store(fos,
"JDK Font Configuration Generated File: *Do Not Edit*");
fos.close();
boolean renamed = tempFile.renameTo(fcInfoFile);
if (!renamed && FontUtilities.debugFonts()) {
System.out.println("rename failed");
warning("Failed renaming file to "+ getFcInfoFile());
}
} catch (Exception e) {
if (FontUtilities.debugFonts()) {
warning("IOException writing to "+ getFcInfoFile());
}
}
}