@Test public void when_endpoint_contains_two_variables_replace_them_all() throws Exception { // GIVEN ConfigLoader.loadMappingsConfig(false); // WHEN MappingEndpoint endpoint = ConfigLoader.getConfig().get(0).getMappingEndpoint("/v0.1/contacts/mobile/support", "GET"); // THEN assertEquals(endpoint.getInternalEndpoint(), "/contacts/mobile/support"); }
@Test public void when_load_read_global_errors() throws Exception { // WHEN ConfigLoader.loadGlobalErrorsConfig(false); // THEN Map<Integer, String> errors = ConfigLoader.getLoadedGlobalErrors(); assertEquals(errors.get(401), "{\"error\":\"custom unauthorized response\"}"); assertEquals(errors.get(404), "{\"error\":\"custom resource not found\"}"); assertEquals(errors.get(500), "{\"error\":\"custom ISE response\"}"); }
@Test public void when_endpoint_contains_RE_return_it_from_RE_mappings() throws Exception { // GIVEN ConfigLoader.loadMappingsConfig(false); // WHEN MappingEndpoint endpoint = ConfigLoader.getConfig().get(0).getMappingEndpoint("/v0.1/payments/12345", "GET"); // THEN assertEquals(endpoint.getInternalEndpoint(), "/payments/12345"); }
public void init(ServletConfig config) throws ServletException { super.init(config); try { String appPath = config.getServletContext().getRealPath(""); // 是否为开发mode debug = "true".equals(config.getInitParameter("development")); // 读取log4j.xml配置文件 DOMConfigurator.configure(appPath + "/WEB-INF/log4j.xml"); logger.info("Starting JForum. Debug mode is " + debug); // ConfigLoader.startSystemglobals(appPath); // 启动缓存引擎 ConfigLoader.startCacheEngine(); // Configure the template engine Configuration templateCfg = new Configuration(); templateCfg.setTemplateUpdateDelay(2); templateCfg.setSetting("number_format", "#"); templateCfg.setSharedVariable("startupTime", new Long(new Date().getTime())); // Create the default template loader String defaultPath = SystemGlobals.getApplicationPath() + "/templates"; FileTemplateLoader defaultLoader = new FileTemplateLoader(new File(defaultPath)); String extraTemplatePath = SystemGlobals.getValue(ConfigKeys.FREEMARKER_EXTRA_TEMPLATE_PATH); if (StringUtils.isNotBlank(extraTemplatePath)) { // An extra template path is configured, we need a MultiTemplateLoader FileTemplateLoader extraLoader = new FileTemplateLoader(new File(extraTemplatePath)); TemplateLoader[] loaders = new TemplateLoader[] {extraLoader, defaultLoader}; MultiTemplateLoader multiLoader = new MultiTemplateLoader(loaders); templateCfg.setTemplateLoader(multiLoader); } else { // An extra template path is not configured, we only need the default loader templateCfg.setTemplateLoader(defaultLoader); } // 载入模块 ModulesRepository.init(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR)); this.loadConfigStuff(); if (!this.debug) { templateCfg.setTemplateUpdateDelay(3600); } JForumExecutionContext.setTemplateConfig(templateCfg); } catch (Exception e) { throw new ForumStartupException("Error while starting JForum", e); } }
protected void maintainVersion() { if (shouldUpdate()) { if (isOutOfDate()) { // we need to update from the default, overriding any out-dated keys loader.updateFromResource(); for (EntryType type : EntryType.values()) { LinkedHashMap<String, ConfigEntry> mappings = loader.getMappings(type); data.put(type, mappings); } } } setDateStamp(); }
@Test public void when_mapping_list_contains_method_and_uri_return_that_mapping_endpoint() throws Exception { // GIVEN ConfigLoader.loadMappingsConfig(false); // WHEN MappingEndpoint meEndpoint = ConfigLoader.getConfig().get(0).getMappingEndpoint("/v0.1/me", "GET"); // THEN assertEquals(meEndpoint.getExternalEndpoint(), "/v0.1/me"); assertEquals(meEndpoint.getMethod(), "GET"); }
/** Retrieve {@link com.opensymphony.module.sitemesh.Decorator} based on 'pattern' tag. */ public Decorator getDecorator(HttpServletRequest request, Page page) { String thisPath = request.getServletPath(); // getServletPath() returns null unless the mapping corresponds to a servlet if (thisPath == null) { String requestURI = request.getRequestURI(); if (request.getPathInfo() != null) { // strip the pathInfo from the requestURI thisPath = requestURI.substring(0, requestURI.indexOf(request.getPathInfo())); } else { thisPath = requestURI; } } else if ("".equals(thisPath)) { // in servlet 2.4, if a request is mapped to '/*', getServletPath returns null (SIM-130) thisPath = request.getPathInfo(); } String name = null; try { name = configLoader.getMappedName(thisPath); } catch (ServletException e) { e.printStackTrace(); } Decorator result = getNamedDecorator(request, name); return result == null ? super.getDecorator(request, page) : result; }
@Test public void when_load_read_mapping() throws Exception { // WHEN ConfigLoader.loadMappingsConfig(false); // THEN List<MappingConfig> config = ConfigLoader.getConfig(); Map<String, String> actions = config.get(0).getActions(); assertEquals(actions.get("ReplaceCustomerId"), "com.apifest.example.ReplaceCustomerIdAction"); assertEquals(actions.get("AddSenderIdInBody"), "com.apifest.example.AddSenderIdInBody"); MappingEndpoint endpoint = config.get(0).getMappingEndpoint("/v0.1/me", "GET"); assertEquals(endpoint.getInternalEndpoint(), "/customer/{customerId}"); assertEquals(endpoint.getAction().getName(), "ReplaceCustomerId"); }
protected void loadConfigStuff() { ConfigLoader.loadUrlPatterns(); I18n.load(); Tpl.load(SystemGlobals.getValue(ConfigKeys.TEMPLATES_MAPPING)); // BB Code BBCodeRepository.setBBCollection(new BBCodeHandler().parse()); }
protected void startApplication() { try { SystemGlobals.loadQueries(SystemGlobals.getValue(ConfigKeys.SQL_QUERIES_GENERIC)); SystemGlobals.loadQueries(SystemGlobals.getValue(ConfigKeys.SQL_QUERIES_DRIVER)); String filename = SystemGlobals.getValue(ConfigKeys.QUARTZ_CONFIG); SystemGlobals.loadAdditionalDefaults(filename); ConfigLoader.createLoginAuthenticator(); ConfigLoader.loadDaoImplementation(); ConfigLoader.listenForChanges(); // ConfigLoader.startSearchIndexer(); ConfigLoader.startSummaryJob(); } catch (Exception e) { throw new ForumStartupException("Error while starting JForum", e); } }
/* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (data == null ? 0 : data.hashCode()); result = prime * result + (factory == null ? 0 : factory.hashCode()); result = prime * result + (filePaths == null ? 0 : filePaths.hashCode()); result = prime * result + (loader == null ? 0 : loader.hashCode()); return result; }
protected void afterInitAppConfig() { JFishProperties loadedConfig = config; Class<ConfigLoader> loaderClass = loadedConfig.getClass(CONFIG_LOADER, null); if (loaderClass != null) { logger.info("load config again by loader: " + loaderClass); configLoader = ReflectUtils.newInstance(loaderClass); Properties properties = configLoader.load(loadedConfig); loadedConfig.putAll(properties); } }
@Test public void when_action_class_is_not_null_do_not_invoke_getAction_from_actions_map() throws Exception { // GIVEN ConfigLoader.loadMappingsConfig(false); MappingAction action = new MappingAction(); action.setName("testAction"); action.setActionClassName("com.apifest.example.AddSenderIdInBodyAction"); ConfigLoader.jarClassLoader = mock(URLClassLoader.class); doReturn(AddSenderIdInBodyAction.class) .when(ConfigLoader.jarClassLoader) .loadClass(action.getActionClassName()); // WHEN BasicAction actionClass = ConfigLoader.getConfig().get(0).getAction(action); // THEN assertTrue(actionClass instanceof AddSenderIdInBodyAction); }
@Test public void when_actionClassname_is_null_get_className_from_actions_config() throws Exception { // GIVEN ConfigLoader.loadMappingsConfig(false); MappingAction mappingAction = new MappingAction(); mappingAction.setName("ReplaceCustomerId"); MappingEndpoint endpoint = new MappingEndpoint(); endpoint.setAction(mappingAction); ConfigLoader.jarClassLoader = mock(URLClassLoader.class); doReturn(ReplaceCustomerIdAction.class) .when(ConfigLoader.jarClassLoader) .loadClass(ReplaceCustomerIdAction.class.getCanonicalName()); // WHEN BasicAction action = ConfigLoader.getConfig().get(0).getAction(mappingAction); // THEN assertTrue(action instanceof ReplaceCustomerIdAction); }
public boolean loadFromConfig() { loader.setForceReload(true); boolean changed = false; synchronized (data) { LinkedHashMap<String, List<String>> oldData = getDataStrings(); data.clear(); for (EntryType type : EntryType.values()) { LinkedHashMap<String, ConfigEntry> mappings = loader.getMappings(type); data.put(type, mappings); } maintainVersion(); LinkedHashMap<String, List<String>> newData = getDataStrings(); changed |= !oldData.equals(newData); if (changed) { savedDataStrings.clear(); savedDataStrings.putAll(newData); } } return changed; }
/** Retrieve Decorator named in 'name' attribute. Checks the role if specified. */ public Decorator getNamedDecorator(HttpServletRequest request, String name) { Decorator result = null; try { result = configLoader.getDecoratorByName(name); } catch (ServletException e) { e.printStackTrace(); } if (result == null || (result.getRole() != null && !request.isUserInRole(result.getRole()))) { // if the result is null or the user is not in the role return super.getNamedDecorator(request, name); } else { return result; } }
@Test public void when_mapping_with_RE_construct_Pattern() throws Exception { // GIVEN MappingEndpoint endpoint = new MappingEndpoint(); endpoint.setExternalEndpoint("/v0.1/payments/{paymentId}"); endpoint.setInternalEndpoint("/v0.1/payments/{paymentId}"); endpoint.setVarExpression("\\d*"); endpoint.setVarName("paymentId"); // WHEN Pattern p = ConfigLoader.constructPattern(endpoint); // THEN assertEquals(p.toString(), "/v0.1/payments/(\\d*)$"); }
/* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj != null && this.getClass().isInstance(obj)) { ConfigManager manager = (ConfigManager) obj; boolean equal = true; equal |= data == manager.data || data != null && data.equals(manager.data); equal |= factory == manager.factory || factory != null && factory.equals(manager.factory); equal |= filePaths == manager.filePaths || filePaths != null && filePaths.equals(manager.filePaths); equal |= loader == manager.loader || loader != null && loader.equals(manager.loader); return equal; } return false; }
@Test public void when_no_custom_jar_do_not_load_custom_class_and_throw_exception() throws Exception { // GIVEN ConfigLoader.jarClassLoader = null; // WHEN String errorMsg = null; try { ConfigLoader.loadCustomClass(AddSenderIdInBodyAction.class.getCanonicalName()); } catch (MappingException e) { errorMsg = e.getMessage(); } // THEN assertEquals(errorMsg, "cannot load custom jar"); }
@Override protected void loadKeys() { ConfigurationSection groups = config.getConfigurationSection("groups"); for (String keys : groups.getKeys(false)) { ConfigurationSection vars = groups.getConfigurationSection(keys); super.plugin .getChatProfiles() .add( new ChatProfile( vars.getName(), vars.getName(), vars.getString("Prefix"), vars.getString("Suffix"), vars.getString("Muffix"), vars.getString("Format"))); } }
public void validate(File masterConfigFile, File contentDir, File templateDir, File outDir) throws ValidationException { if (!contentDir.exists() || !contentDir.isDirectory()) { throw new ValidationException("Content directory not available."); } if (!templateDir.exists() || !templateDir.isDirectory()) { throw new ValidationException("Template directory not available."); } if (!masterConfigFile.isFile()) { throw new ValidationException( MessageFormat.format( "Configuration file `{0}{1}' not available.", Constants.MASTER_CONFIG, exeConfig.getFileExtension())); } if (!cliCmd.force) { if (!Util.isDirEmptyOrNotExists(outDir)) { throw new ValidationException("Target directory not empty. Stopping..."); } } }
protected void reload() { super.rereadFromDisk(); super.load(); super.plugin.log("Variables reloaded from disk!"); }
public static void loadConfig(String configFile, int refreshInterval) { XMLPropertiesConfiguration conf = ConfigLoader.loadXMLPropertiesConfiguration(configFile, refreshInterval); WebConfig.setConfig(conf); }
@Override protected void loadFile() { super.loadFile(); FileConfiguration internalConfig = YamlConfiguration.loadConfiguration(plugin.getResource(fileName)); Set<String> configKeys = config.getKeys(true); Set<String> internalConfigKeys = internalConfig.getKeys(true); boolean needSave = false; Set<String> oldKeys = new HashSet<String>(configKeys); oldKeys.removeAll(internalConfigKeys); Set<String> newKeys = new HashSet<String>(internalConfigKeys); newKeys.removeAll(configKeys); // Don't need a re-save if we have old keys sticking around? // Would be less saving, but less... correct? if (!newKeys.isEmpty() || !oldKeys.isEmpty()) { needSave = true; } for (String key : oldKeys) { plugin.debug("Removing unused key: " + key); config.set(key, null); } for (String key : newKeys) { plugin.debug("Adding new key: " + key + " = " + internalConfig.get(key)); config.set(key, internalConfig.get(key)); } if (needSave) { // Get Bukkit's version of an acceptable config with new keys, and no old keys String output = config.saveToString(); // Convert to the superior 4 space indentation output = output.replace(" ", " "); // Rip out Bukkit's attempt to save comments at the top of the file while (output.indexOf('#') != -1) { output = output.substring(output.indexOf('\n', output.indexOf('#')) + 1); } // Read the internal config to get comments, then put them in the new one try { // Read internal BufferedReader reader = new BufferedReader(new InputStreamReader(plugin.getResource(fileName))); HashMap<String, String> comments = new HashMap<String, String>(); String temp = ""; String line; while ((line = reader.readLine()) != null) { if (line.contains("#")) { temp += line + "\n"; } else if (line.contains(":")) { line = line.substring(0, line.indexOf(":") + 1); if (!temp.isEmpty()) { comments.put(line, temp); temp = ""; } } } // Dump to the new one for (String key : comments.keySet()) { if (output.contains(key)) { output = output.substring(0, output.indexOf(key)) + comments.get(key) + output.substring(output.indexOf(key)); } } } catch (Exception e) { e.printStackTrace(); } // Save it try { String saveName = fileName; // At this stage we cannot guarantee that Config has been loaded, so we do the check // directly here if (!plugin.getConfig().getBoolean("General.Config_Update_Overwrite", true)) { saveName += ".new"; } BufferedWriter writer = new BufferedWriter(new FileWriter(new File(plugin.getDataFolder(), saveName))); writer.write(output); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
/** * Load the configuration * * @return JsonObject with the configuration */ protected JsonObject loadConfiguration() { return ConfigLoader.loadConfiguration(); }
public static void init() { PropertyConfigurator.configure("./etc/log4j.properties"); ConfigLoader.init(); Messages.loadClientMessages(); Messages.loadServerMessages(); HibernateUtils.getSessionFactory(); CmdContainer container = CmdContainer.getInstance(); container.buildList(); ClassLoader cl = ClassLoader.getSystemClassLoader(); String javaClassPath = System.getProperty("java.class.path"); String userDirectory = System.getProperty("user.dir"); String separator = System.getProperty("file.separator"); String pathSeparator = System.getProperty("path.separator"); javaClassPath = javaClassPath.replace('\\', separator.charAt(0)); javaClassPath = javaClassPath.replace('/', separator.charAt(0)); if (!userDirectory.endsWith(separator)) { userDirectory = userDirectory + separator; } myPath = userDirectory + javaClassPath; // log.debug(myPath); int x = myPath.lastIndexOf(separator.charAt(0)); if (x != -1) { myPath = myPath.substring(0, x + 1); } if (javaClassPath.matches("[a-zA-Z]:\\\\.*")) { int y = javaClassPath.indexOf(';'); while (y != -1) { javaClassPath = javaClassPath.substring(y + 1, javaClassPath.length()); y = javaClassPath.indexOf(';'); } myPath = javaClassPath; if (myPath.endsWith(".jar") || myPath.endsWith(".jar" + separator)) { myPath = myPath.substring(0, myPath.lastIndexOf(separator)); } if (!myPath.endsWith(separator)) { myPath = myPath + separator; } log.debug(myPath); if (myPath.equals("\\")) { myPath = ""; } } if (System.getProperty("os.name").equalsIgnoreCase("Linux")) { if (!javaClassPath.startsWith(separator)) { StringTokenizer st1 = new StringTokenizer(myPath, pathSeparator); String aux = st1.nextToken(); log.debug(myPath); while (!(aux.toLowerCase().contains("dshub.jar".toLowerCase())) && st1.hasMoreTokens()) { aux = st1.nextToken(); } // if(!st1.hasMoreTokens()) // Main.PopMsg("FAIL. Java Classpath Error."); // return; myPath = aux; } else { if (javaClassPath.toLowerCase().endsWith("/dshub.jar")) { myPath = javaClassPath.substring(0, javaClassPath.length() - 9); } else { myPath = javaClassPath; } } } if (System.getProperty("os.name").equalsIgnoreCase("sunos")) { if (javaClassPath.startsWith(separator)) { if (javaClassPath.toLowerCase().endsWith("/dshub.jar")) { myPath = javaClassPath.substring(0, javaClassPath.length() - 9); } else { myPath = javaClassPath; } } } // log.debug(myPath); pManager = new PythonManager(); }
public ConfigSettings(ColoredGroups plugin, String fileName) { super(plugin, fileName); config = plugin.getConfig(); super.saveIfNotExist(); }
public Config() { descriptor = ConfigLoader.loadFromRuntimeProperties(); }