List of usage examples for java.util Properties remove
@Override public synchronized Object remove(Object key)
From source file:org.schemaspy.Config.java
/** * Determines the database properties associated with the specified type. * A call to {@link #setDbProperties(Properties)} is expected after determining * the complete set of properties./*from ww w.j ava2 s. co m*/ * * @param type * @return * @throws IOException * @throws InvalidConfigurationException if db properties are incorrectly formed */ public Properties determineDbProperties(String type) throws IOException, InvalidConfigurationException { ResourceBundle bundle = null; try { File propertiesFile = new File(type); bundle = new PropertyResourceBundle(new FileInputStream(propertiesFile)); dbPropertiesLoadedFrom = propertiesFile.getAbsolutePath(); } catch (FileNotFoundException notFoundOnFilesystemWithoutExtension) { try { File propertiesFile = new File(type + ".properties"); bundle = new PropertyResourceBundle(new FileInputStream(propertiesFile)); dbPropertiesLoadedFrom = propertiesFile.getAbsolutePath(); } catch (FileNotFoundException notFoundOnFilesystemWithExtensionTackedOn) { try { bundle = ResourceBundle.getBundle(type); dbPropertiesLoadedFrom = "[" + getLoadedFromJar() + "]" + File.separator + type + ".properties"; } catch (Exception notInJarWithoutPath) { try { String path = TableOrderer.class.getPackage().getName() + ".types." + type; path = path.replace('.', '/'); bundle = ResourceBundle.getBundle(path); dbPropertiesLoadedFrom = "[" + getLoadedFromJar() + "]/" + path + ".properties"; } catch (Exception notInJar) { notInJar.printStackTrace(); notFoundOnFilesystemWithExtensionTackedOn.printStackTrace(); throw notFoundOnFilesystemWithoutExtension; } } } } Properties props = asProperties(bundle); bundle = null; String saveLoadedFrom = dbPropertiesLoadedFrom; // keep original thru recursion // bring in key/values pointed to by the include directive // example: include.1=mysql::selectRowCountSql for (int i = 1; true; ++i) { String include = (String) props.remove("include." + i); if (include == null) break; int separator = include.indexOf("::"); if (separator == -1) throw new InvalidConfigurationException("include directive in " + dbPropertiesLoadedFrom + " must have '::' between dbType and key"); String refdType = include.substring(0, separator).trim(); String refdKey = include.substring(separator + 2).trim(); // recursively resolve the ref'd properties file and the ref'd key Properties refdProps = determineDbProperties(refdType); props.put(refdKey, refdProps.getProperty(refdKey)); } // bring in base properties files pointed to by the extends directive String baseDbType = (String) props.remove("extends"); if (baseDbType != null) { baseDbType = baseDbType.trim(); Properties baseProps = determineDbProperties(baseDbType); // overlay our properties on top of the base's baseProps.putAll(props); props = baseProps; } // done with this level of recursion...restore original dbPropertiesLoadedFrom = saveLoadedFrom; // this won't be correct until the final recursion exits dbProperties = props; return props; }
From source file:org.apache.sqoop.SqoopOptions.java
/** * This method encodes the property key values found in the provided * properties instance <tt>values</tt> into another properties instance * <tt>props</tt>. The specified <tt>prefix</tt> is used as a namespace * qualifier for keys when inserting. This allows easy introspection of the * property key values in <tt>props</tt> instance to later separate out all * the properties that belong to the <tt>values</tt> instance. * @param props the container properties instance * @param prefix the prefix for qualifying contained property keys. * @param values the contained properties instance, all of whose elements will * be added to the container properties instance. * * @see #getPropertiesAsNetstedProperties(Properties, String) *//*from w ww . j a v a2 s. c o m*/ private void setPropertiesAsNestedProperties(Properties props, String prefix, Properties values) { String nestedPropertyPrefix = prefix + "."; if (null == values || values.size() == 0) { Iterator<String> it = props.stringPropertyNames().iterator(); while (it.hasNext()) { String name = it.next(); if (name.startsWith(nestedPropertyPrefix)) { props.remove(name); } } } else { Iterator<String> it = values.stringPropertyNames().iterator(); while (it.hasNext()) { String name = it.next(); putProperty(props, nestedPropertyPrefix + name, values.getProperty(name)); } } }
From source file:org.artifactory.common.property.ArtifactorySystemProperties.java
public void loadArtifactorySystemProperties(File systemPropertiesFile, File artifactoryPropertiesFile) { Properties combinedProperties = new Properties(); if (systemPropertiesFile != null && systemPropertiesFile.exists()) { FileInputStream fis = null; try {/*from w w w. ja va2 s. c o m*/ fis = new FileInputStream(systemPropertiesFile); combinedProperties.load(fis); } catch (Exception e) { throw new RuntimeException("Could not read default system properties from '" + systemPropertiesFile.getAbsolutePath() + "'.", e); } finally { IOUtils.closeQuietly(fis); } } // load artifactory.properties (version and revision properties) if (artifactoryPropertiesFile != null && artifactoryPropertiesFile.exists()) { FileInputStream fis = null; try { // Load from file than override from the system props fis = new FileInputStream(artifactoryPropertiesFile); combinedProperties.load(fis); } catch (Exception e) { throw new RuntimeException("Could not read artifactory.properties from '" + artifactoryPropertiesFile.getAbsolutePath() + "'.", e); } finally { IOUtils.closeQuietly(fis); } } // Override with System properties loadSystemProperties(combinedProperties); Set<String> setAsSystemProp = new HashSet<>(); //Cleanup all non-artifactory system properties and set them as system properties for (Object key : combinedProperties.keySet()) { String propName = (String) key; String propValue = combinedProperties.getProperty(propName); if (!propName.startsWith(ConstantValues.SYS_PROP_PREFIX)) { // TODO: mainly for derby db properties, find another way of doing it System.setProperty(propName, propValue); setAsSystemProp.add(propName); } } for (String key : setAsSystemProp) { combinedProperties.remove(key); } substituteRepoKeys = fillRepoKeySubstitute(combinedProperties); //Test for deprecated properties and warn handleDeprecatedProps(combinedProperties); validateConstants(combinedProperties); // Use the EnumMap as much as possible EnumMap<ConstantValues, String> newArtifactoryProperties = new EnumMap<>(ConstantValues.class); for (ConstantValues constVal : ConstantValues.values()) { Object val = combinedProperties.remove(constVal.getPropertyName()); if (val != null) { newArtifactoryProperties.put(constVal, (String) val); } } artifactoryProperties = newArtifactoryProperties; // TODO: Print a message when combined props is not empty as this should not happen. // It's probably a typo! But it's used for special security access values not declared in ConstantValues nonEnumArtifactoryProperties = combinedProperties; artifactoryBooleanProperties.clear(); artifactoryLongProperties.clear(); }
From source file:com.adito.jdbc.DBUpgrader.java
/** * Check the database schema and perform any upgrades. * /*from w w w. j a va2s .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:org.kuali.rice.krad.web.controller.UifControllerBase.java
/** * Builds up a URL to the lookup view based on the given post action * parameters and redirects//from ww w. j ava 2s . c o m */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=performLookup") public ModelAndView performLookup(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) { Properties lookupParameters = form.getActionParametersAsProperties(); String lookupObjectClassName = (String) lookupParameters.get(UifParameters.DATA_OBJECT_CLASS_NAME); Class<?> lookupObjectClass = null; try { lookupObjectClass = Class.forName(lookupObjectClassName); } catch (ClassNotFoundException e) { LOG.error("Unable to get class for name: " + lookupObjectClassName); throw new RuntimeException("Unable to get class for name: " + lookupObjectClassName, e); } // get form values for the lookup parameter fields String lookupParameterString = (String) lookupParameters.get(UifParameters.LOOKUP_PARAMETERS); if (lookupParameterString != null) { Map<String, String> lookupParameterFields = KRADUtils.getMapFromParameterString(lookupParameterString); for (Entry<String, String> lookupParameter : lookupParameterFields.entrySet()) { String lookupParameterValue = LookupUtils.retrieveLookupParameterValue(form, request, lookupObjectClass, lookupParameter.getValue(), lookupParameter.getKey()); if (StringUtils.isNotBlank(lookupParameterValue)) { lookupParameters.put( UifPropertyPaths.LOOKUP_CRITERIA + "['" + lookupParameter.getValue() + "']", lookupParameterValue); } } lookupParameters.remove(UifParameters.LOOKUP_PARAMETERS); } String baseLookupUrl = (String) lookupParameters.get(UifParameters.BASE_LOOKUP_URL); lookupParameters.remove(UifParameters.BASE_LOOKUP_URL); // set lookup method to call lookupParameters.put(UifParameters.METHOD_TO_CALL, UifConstants.MethodToCallNames.START); String autoSearchString = (String) lookupParameters.get(UifParameters.AUTO_SEARCH); if (Boolean.parseBoolean(autoSearchString)) { lookupParameters.put(UifParameters.METHOD_TO_CALL, UifConstants.MethodToCallNames.SEARCH); } lookupParameters.put(UifParameters.RETURN_LOCATION, form.getFormPostUrl()); lookupParameters.put(UifParameters.RETURN_FORM_KEY, form.getFormKey()); // special check for external object classes if (lookupObjectClass != null) { ModuleService responsibleModuleService = KRADServiceLocatorWeb.getKualiModuleService() .getResponsibleModuleService(lookupObjectClass); if (responsibleModuleService != null && responsibleModuleService.isExternalizable(lookupObjectClass)) { String lookupUrl = responsibleModuleService.getExternalizableDataObjectLookupUrl(lookupObjectClass, lookupParameters); return performRedirect(form, lookupUrl, new Properties()); } } return performRedirect(form, baseLookupUrl, lookupParameters); }
From source file:org.olat.core.util.i18n.I18nManager.java
/** * Enable or disable the inline translation mode for a specific key. If * disabled, the inline translation mode will not be available for this key. * <p>/*w w w. j av a 2s. c om*/ * Disable inline translation for keys that have issues with the inline * translation system such as default values that are used in forms that * have length checks. * * @param bundleName * @param key * @param enable */ public void setInlineTranslationEnabledForKey(String bundleName, String key, boolean enable) { Properties metadataProperties = getPropertiesWithoutResolvingRecursively(null, bundleName); String propertyKey = key + METADATA_KEY_INLINEREANSLATION_POSTFIX; if (enable) { if (metadataProperties.contains(propertyKey)) { metadataProperties.remove(propertyKey); } } else { metadataProperties.setProperty(propertyKey, METADATA_KEY_INLINEREANSLATION_VALUE_DISABLED); } saveOrUpdateProperties(metadataProperties, null, bundleName); }
From source file:org.oscarehr.common.web.PregnancyAction.java
public ActionForward saveFormAjax(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { int newID = 0; FrmRecord rec = null;//from www .j a v a 2 s. co m JSONObject jsonObj = null; try { FrmRecordFactory recorder = new FrmRecordFactory(); rec = recorder.factory(request.getParameter("form_class")); Properties props = new Properties(); boolean bMulPage = request.getParameter("c_lastVisited") != null ? true : false; String name; if (bMulPage) { String curPageNum = request.getParameter("c_lastVisited"); String commonField = request.getParameter("commonField") != null ? request.getParameter("commonField") : "&'"; curPageNum = curPageNum.length() > 3 ? ("" + curPageNum.charAt(0)) : curPageNum; //copy an old record props = rec.getFormRecord(Integer.parseInt(request.getParameter("demographic_no")), Integer.parseInt(request.getParameter("formId"))); //empty the current page Properties currentParam = new Properties(); for (Enumeration varEnum = request.getParameterNames(); varEnum.hasMoreElements();) { name = (String) varEnum.nextElement(); currentParam.setProperty(name, ""); } for (Enumeration varEnum = props.propertyNames(); varEnum.hasMoreElements();) { name = (String) varEnum.nextElement(); // kick off the current page elements, commonField on the current page if (name.startsWith(curPageNum + "_") || (name.startsWith(commonField) && currentParam.containsKey(name))) { props.remove(name); } } } //update the current record for (Enumeration varEnum = request.getParameterNames(); varEnum.hasMoreElements();) { name = (String) varEnum.nextElement(); props.setProperty(name, request.getParameter(name)); } props.setProperty("provider_no", (String) request.getSession().getAttribute("user")); newID = rec.saveFormRecord(props); String ip = request.getRemoteAddr(); LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.ADD, request.getParameter("form_class"), "" + newID, ip, request.getParameter("demographic_no")); jsonObj = JSONObject.fromObject(new LabelValueBean("result", String.valueOf(newID))); } catch (Exception ex) { MiscUtils.getLogger().error("error", ex); jsonObj = JSONObject.fromObject(new LabelValueBean("result", "error")); } response.getWriter().print(jsonObj.toString()); return null; }
From source file:org.hyperic.hq.product.RtPlugin.java
protected ParsedFile[] generateFileList(Properties alreadyParsedFiles, String logdir, String logmask) throws IOException { FilenameFilter filter = new GlobFilenameFilter(logmask.trim()); ArrayList removedFiles = new ArrayList(); Enumeration en = alreadyParsedFiles.keys(); while (en.hasMoreElements()) { String file = (String) en.nextElement(); File temp = new File(file); if (filter.accept(temp.getParentFile(), temp.getName())) { removedFiles.add(file);/*from w w w. j a va2 s . com*/ } } File directory = new File(logdir); if (!directory.canRead()) { this.log.error("logDir (" + logdir + ") is not readable by the agent!"); } File[] flist = directory.listFiles(filter); ArrayList toParse = new ArrayList(); if (flist == null || flist.length == 0) { this.log.warn("No valid response time log files found. " + "logDir='" + logdir + "', logMask='" + logmask + "'"); return (ParsedFile[]) toParse.toArray(new ParsedFile[0]); } for (int i = 0; i < flist.length; i++) { Long len = new Long(flist[i].length()); String canonPath = flist[i].getCanonicalPath(); String value = alreadyParsedFiles.getProperty(canonPath); Long oldlen = (value == null) ? new Long(0) : Long.valueOf(value); // This file exists, remove it from the list of files // that have been removed. removedFiles.remove(canonPath); if (oldlen.compareTo(len) != 0) { this.log.debug("Adding " + canonPath + " to parse list " + "(offset=" + oldlen + ")"); toParse.add(new ParsedFile(canonPath, oldlen.longValue())); } } // Remove the files that were removed since the last time we parsed // the logs. The way this 'removed files' thing is implemented is // soo lame. Iterator it = removedFiles.iterator(); while (it.hasNext()) { String toRemove = (String) it.next(); this.log.debug("Removing " + toRemove + " from parse list"); this.log.debug(toRemove); alreadyParsedFiles.remove(toRemove); } return (ParsedFile[]) toParse.toArray(new ParsedFile[0]); }
From source file:org.jahia.modules.external.modules.ModulesDataSource.java
private void saveProperties(ExternalData data) throws RepositoryException { OutputStream outputStream = null; try {// www.j av a 2 s .c o m ExtendedNodeType propertiesType = NodeTypeRegistry.getInstance() .getNodeType(Constants.JAHIAMIX_VIEWPROPERTIES); Map<String, ExtendedPropertyDefinition> propertyDefinitionMap = propertiesType .getDeclaredPropertyDefinitionsAsMap(); Properties properties = new SortedProperties(); for (Map.Entry<String, String[]> property : data.getProperties().entrySet()) { if (propertyDefinitionMap.containsKey(property.getKey())) { String[] v = property.getValue(); if (v != null) { String propertyValue = StringUtils.join(v, ","); if (propertyDefinitionMap.get(property.getKey()).getRequiredType() != PropertyType.BOOLEAN || !propertyValue.equals("false")) { properties.put(property.getKey(), propertyValue); } } } } FileObject file = getFile(StringUtils.substringBeforeLast(data.getPath(), ".") + PROPERTIES_EXTENSION); Properties original = new Properties(); if (file.exists()) { original.load(file.getContent().getInputStream()); for (String s : propertyDefinitionMap.keySet()) { original.remove(s); } } properties.putAll(original); if (!properties.isEmpty()) { outputStream = file.getContent().getOutputStream(); properties.store(outputStream, data.getPath()); } else { if (file.exists()) { file.delete(); } } ResourceBundle.clearCache(); } catch (FileSystemException e) { logger.error(e.getMessage(), e); throw new RepositoryException("Failed to write source code", e); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RepositoryException("Failed to write source code", e); } catch (NoSuchNodeTypeException e) { logger.error("Unable to find type : " + data.getType() + " for node " + data.getPath(), e); throw e; } finally { IOUtils.closeQuietly(outputStream); } }
From source file:org.apache.solr.update.InvenioKeepRecidUpdated.java
private void runSynchronously(Map<String, Object> data, SolrQueryRequest req) throws MalformedURLException, IOException, InterruptedException { log.info("============================================================================="); log.info(data.toString());//from w w w .j av a 2 s .c om log.info(req.toString()); log.info(req.getParamString()); log.info("============================================================================="); SolrParams params = req.getParams(); SolrCore core = req.getCore(); String importurl = params.get(PARAM_IMPORT, null); String updateurl = params.get(PARAM_UPDATE, null); String deleteurl = params.get(PARAM_DELETE, null); @SuppressWarnings("unchecked") HashMap<String, int[]> dictData = (HashMap<String, int[]>) data.get("dictData"); Properties prop = (Properties) req.getContext().get(IKRU_PROPERTIES); if (dictData.containsKey(ADDED) && dictData.get(ADDED).length > 0) { setWorkerMessage("Phase 1/3. Adding records: " + dictData.get(ADDED).length); if (importurl != null) { if (importurl.equals("blankrecords")) { runProcessingAdded(dictData.get(ADDED), req); } else { runProcessing(core, importurl, dictData.get(ADDED), req); } } } if (dictData.containsKey(UPDATED) && dictData.get(UPDATED).length > 0) { setWorkerMessage("Phase 2/3. Updating records: " + dictData.get(UPDATED).length); if (updateurl != null) { if (updateurl.equals("blankrecords")) { runProcessingUpdated(dictData.get(UPDATED), req); } else { runProcessing(core, updateurl, dictData.get(UPDATED), req); } } } if (dictData.containsKey(DELETED) && dictData.get(DELETED).length > 0) { setWorkerMessage("Phase 3/3. deleting records: " + dictData.get(DELETED).length); if (deleteurl != null) { if (deleteurl.equals("blankrecords")) { runProcessingDeleted(dictData.get(DELETED), req); } else { runProcessing(core, deleteurl, dictData.get(DELETED), req); } } } // save the state into the properties (the modification date must be there // in all situations prop.put(LAST_UPDATE, (String) data.get(LAST_UPDATE)); prop.put(LAST_RECID, String.valueOf((Integer) data.get(LAST_RECID))); prop.remove(PARAM_BATCHSIZE); prop.remove(PARAM_MAXIMPORT); prop.remove(PARAM_TOKEN); saveProperties(prop); if (params.getBool(PARAM_COMMIT, false)) { setWorkerMessage("Phase 3/3. Writing index..."); CommitUpdateCommand updateCmd = new CommitUpdateCommand(req, false); req.getCore().getUpdateHandler().commit(updateCmd); } }