Java tutorial
/** * Copyright 2012 the project-owners * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package inti.ws.spring.resource.config; import inti.ws.spring.resource.WebResource; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @Component public class ConfigParserProvider { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigParserProvider.class); protected ObjectMapper mapper = new ObjectMapper(); @Inject ApplicationContext context; public Map<String, ConfigParser<? extends WebResource>> getConfigParsers(ClassLoader classLoader) throws Exception { Enumeration<URL> parserLocations = classLoader.getResources("META-INF/inti.ws.spring.resource/parser.json"); URL url; ConfigParserSettings settings = null; InputStream inputStream; JsonNode node; Entry<String, JsonNode> field; Iterator<Entry<String, JsonNode>> fields; Map<String, ConfigParser<? extends WebResource>> parsers = new HashMap<>(); ConfigParser<? extends WebResource> parser; while (parserLocations.hasMoreElements()) { url = parserLocations.nextElement(); LOGGER.debug("getConfigParsers - scanning url={}", url); inputStream = url.openStream(); try { node = mapper.readTree(inputStream); fields = node.fields(); while (fields.hasNext()) { field = fields.next(); settings = mapper.convertValue(field.getValue(), ConfigParserSettings.class); parser = context.getBean(settings.getConfigurator()); parser.setConfigParserSettings(settings); if (parsers.containsKey(field.getKey())) { throw new RuntimeException( "name collision detected: '" + field.getKey() + "' already engaged."); } LOGGER.debug("getConfigParsers - found parser for key={}: {}", field.getKey(), parser); parsers.put(field.getKey(), parser); } } finally { inputStream.close(); } } return parsers; } }