use of java.util.Map in project camel by apache.
the class DefaultCamelContext method explainEndpointJson.
// CHECKSTYLE:OFF
public String explainEndpointJson(String uri, boolean includeAllOptions) {
try {
URI u = new URI(uri);
String json = getComponentParameterJsonSchema(u.getScheme());
if (json == null) {
return null;
}
List<Map<String, String>> rows = JsonSchemaHelper.parseJsonSchema("properties", json, true);
// selected rows to use for answer
Map<String, String[]> selected = new LinkedHashMap<String, String[]>();
Map<String, String[]> uriOptions = new LinkedHashMap<String, String[]>();
// insert values from uri
Map<String, Object> options = EndpointHelper.endpointProperties(this, uri);
// extract consumer. prefix options
Map<String, Object> consumerOptions = IntrospectionSupport.extractProperties(options, "consumer.");
// and add back again without the consumer. prefix as that json schema omits that
options.putAll(consumerOptions);
for (Map.Entry<String, Object> entry : options.entrySet()) {
String name = entry.getKey();
String value = "";
if (entry.getValue() != null) {
value = entry.getValue().toString();
}
value = URISupport.sanitizePath(value);
// find type and description from the json schema
String type = null;
String kind = null;
String group = null;
String label = null;
String required = null;
String javaType = null;
String deprecated = null;
String secret = null;
String defaultValue = null;
String description = null;
for (Map<String, String> row : rows) {
if (name.equals(row.get("name"))) {
type = row.get("type");
kind = row.get("kind");
group = row.get("group");
label = row.get("label");
required = row.get("required");
javaType = row.get("javaType");
deprecated = row.get("deprecated");
secret = row.get("secret");
defaultValue = row.get("defaultValue");
description = row.get("description");
break;
}
}
// remember this option from the uri
uriOptions.put(name, new String[] { name, kind, group, label, required, type, javaType, deprecated, secret, value, defaultValue, description });
}
// include other rows
for (Map<String, String> row : rows) {
String name = row.get("name");
String kind = row.get("kind");
String group = row.get("group");
String label = row.get("label");
String required = row.get("required");
String value = row.get("value");
String defaultValue = row.get("defaultValue");
String type = row.get("type");
String javaType = row.get("javaType");
String deprecated = row.get("deprecated");
String secret = row.get("secret");
value = URISupport.sanitizePath(value);
String description = row.get("description");
boolean isUriOption = uriOptions.containsKey(name);
// always include from uri or path options
if (includeAllOptions || isUriOption || "path".equals(kind)) {
if (!selected.containsKey(name)) {
// add as selected row, but take the value from uri options if it was from there
if (isUriOption) {
selected.put(name, uriOptions.get(name));
} else {
selected.put(name, new String[] { name, kind, group, label, required, type, javaType, deprecated, secret, value, defaultValue, description });
}
}
}
}
// skip component properties
json = ObjectHelper.before(json, " \"componentProperties\": {");
// and rewrite properties
StringBuilder buffer = new StringBuilder(" \"properties\": {");
boolean first = true;
for (String[] row : selected.values()) {
if (first) {
first = false;
} else {
buffer.append(",");
}
buffer.append("\n ");
String name = row[0];
String kind = row[1];
String group = row[2];
String label = row[3];
String required = row[4];
String type = row[5];
String javaType = row[6];
String deprecated = row[7];
String secret = row[8];
String value = row[9];
String defaultValue = row[10];
String description = row[11];
// add json of the option
buffer.append(StringQuoteHelper.doubleQuote(name)).append(": { ");
CollectionStringBuffer csb = new CollectionStringBuffer();
if (kind != null) {
csb.append("\"kind\": \"" + kind + "\"");
}
if (group != null) {
csb.append("\"group\": \"" + group + "\"");
}
if (label != null) {
csb.append("\"label\": \"" + label + "\"");
}
if (required != null) {
csb.append("\"required\": \"" + required + "\"");
}
if (type != null) {
csb.append("\"type\": \"" + type + "\"");
}
if (javaType != null) {
csb.append("\"javaType\": \"" + javaType + "\"");
}
if (deprecated != null) {
csb.append("\"deprecated\": \"" + deprecated + "\"");
}
if (secret != null) {
csb.append("\"secret\": \"" + secret + "\"");
}
if (value != null) {
csb.append("\"value\": \"" + value + "\"");
}
if (defaultValue != null) {
csb.append("\"defaultValue\": \"" + defaultValue + "\"");
}
if (description != null) {
csb.append("\"description\": \"" + description + "\"");
}
if (!csb.isEmpty()) {
buffer.append(csb.toString());
}
buffer.append(" }");
}
buffer.append("\n }\n}\n");
// insert the original first part of the json into the start of the buffer
buffer.insert(0, json);
return buffer.toString();
} catch (Exception e) {
// ignore and return empty response
return null;
}
}
use of java.util.Map in project camel by apache.
the class DefaultCamelContext method removeRoute.
public synchronized boolean removeRoute(String routeId) throws Exception {
// remove the route from ErrorHandlerBuilder if possible
if (getErrorHandlerBuilder() instanceof ErrorHandlerBuilderSupport) {
ErrorHandlerBuilderSupport builder = (ErrorHandlerBuilderSupport) getErrorHandlerBuilder();
builder.removeOnExceptionList(routeId);
}
// gather a map of all the endpoints in use by the routes, so we can known if a given endpoints is in use
// by one or more routes, when we remove the route
Map<String, Set<Endpoint>> endpointsInUse = new HashMap<String, Set<Endpoint>>();
for (Map.Entry<String, RouteService> entry : routeServices.entrySet()) {
endpointsInUse.put(entry.getKey(), entry.getValue().gatherEndpoints());
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
if (getRouteStatus(routeId).isStopped()) {
routeService.setRemovingRoutes(true);
shutdownRouteService(routeService);
removeRouteDefinition(routeId);
routeServices.remove(routeId);
// remove route from startup order as well, as it was removed
Iterator<RouteStartupOrder> it = routeStartupOrder.iterator();
while (it.hasNext()) {
RouteStartupOrder order = it.next();
if (order.getRoute().getId().equals(routeId)) {
it.remove();
}
}
// from the route which we have removed, then remove all its private endpoints
// (eg the endpoints which are not in use by other routes)
Set<Endpoint> toRemove = new LinkedHashSet<Endpoint>();
for (Endpoint endpoint : endpointsInUse.get(routeId)) {
// how many times is the endpoint in use
int count = 0;
for (Set<Endpoint> endpoints : endpointsInUse.values()) {
if (endpoints.contains(endpoint)) {
count++;
}
}
// notice we will count ourselves so if there is only 1 then its safe to remove
if (count <= 1) {
toRemove.add(endpoint);
}
}
for (Endpoint endpoint : toRemove) {
log.debug("Removing: {} which was only in use by route: {}", endpoint, routeId);
removeEndpoint(endpoint);
}
return true;
} else {
return false;
}
}
return false;
}
use of java.util.Map in project camel by apache.
the class DefaultRuntimeEndpointRegistry method notify.
@Override
public void notify(EventObject event) throws Exception {
if (event instanceof RouteAddedEvent) {
RouteAddedEvent rse = (RouteAddedEvent) event;
Endpoint endpoint = rse.getRoute().getEndpoint();
String routeId = rse.getRoute().getId();
// a HashSet is fine for inputs as we only have a limited number of those
Set<String> uris = new HashSet<String>();
uris.add(endpoint.getEndpointUri());
inputs.put(routeId, uris);
// use a LRUCache for outputs as we could potential have unlimited uris if dynamic routing is in use
// and therefore need to have the limit in use
outputs.put(routeId, new LRUCache<String, String>(limit));
} else if (event instanceof RouteRemovedEvent) {
RouteRemovedEvent rse = (RouteRemovedEvent) event;
String routeId = rse.getRoute().getId();
inputs.remove(routeId);
outputs.remove(routeId);
if (extended) {
String uri = rse.getRoute().getEndpoint().getEndpointUri();
String key = asUtilizationKey(routeId, uri);
if (key != null) {
inputUtilization.remove(key);
}
}
} else if (extended && event instanceof ExchangeCreatedEvent) {
// we only capture details in extended mode
ExchangeCreatedEvent ece = (ExchangeCreatedEvent) event;
Endpoint endpoint = ece.getExchange().getFromEndpoint();
if (endpoint != null) {
String routeId = ece.getExchange().getFromRouteId();
String uri = endpoint.getEndpointUri();
String key = asUtilizationKey(routeId, uri);
if (key != null) {
inputUtilization.onHit(key);
}
}
} else if (event instanceof ExchangeSendingEvent) {
ExchangeSendingEvent ese = (ExchangeSendingEvent) event;
Endpoint endpoint = ese.getEndpoint();
String routeId = getRouteId(ese.getExchange());
String uri = endpoint.getEndpointUri();
Map<String, String> uris = outputs.get(routeId);
if (uris != null && !uris.containsKey(uri)) {
uris.put(uri, uri);
}
if (extended) {
String key = asUtilizationKey(routeId, uri);
if (key != null) {
outputUtilization.onHit(key);
}
}
}
}
use of java.util.Map in project camel by apache.
the class DefaultExceptionPolicyStrategy method findMatchedExceptionPolicy.
private boolean findMatchedExceptionPolicy(Map<ExceptionPolicyKey, OnExceptionDefinition> exceptionPolicies, Exchange exchange, Throwable exception, Map<Integer, OnExceptionDefinition> candidates) {
if (LOG.isTraceEnabled()) {
LOG.trace("Finding best suited exception policy for thrown exception {}", exception.getClass().getName());
}
// the goal is to find the exception with the same/closet inheritance level as the target exception being thrown
int targetLevel = getInheritanceLevel(exception.getClass());
// candidate is the best candidate found so far to return
OnExceptionDefinition candidate = null;
// difference in inheritance level between the current candidate and the thrown exception (target level)
int candidateDiff = Integer.MAX_VALUE;
// loop through all the entries and find the best candidates to use
Set<Map.Entry<ExceptionPolicyKey, OnExceptionDefinition>> entries = exceptionPolicies.entrySet();
for (Map.Entry<ExceptionPolicyKey, OnExceptionDefinition> entry : entries) {
Class<?> clazz = entry.getKey().getExceptionClass();
OnExceptionDefinition type = entry.getValue();
// so we will not pick an OnException from another route
if (exchange != null && exchange.getUnitOfWork() != null && type.isRouteScoped()) {
RouteDefinition route = exchange.getUnitOfWork().getRouteContext() != null ? exchange.getUnitOfWork().getRouteContext().getRoute() : null;
RouteDefinition typeRoute = ProcessorDefinitionHelper.getRoute(type);
if (route != null && typeRoute != null && route != typeRoute) {
if (LOG.isTraceEnabled()) {
LOG.trace("The type is scoped for route: {} however Exchange is at route: {}", typeRoute.getId(), route.getId());
}
continue;
}
}
if (filter(type, clazz, exception)) {
// must match
if (!matchesWhen(type, exchange)) {
LOG.trace("The type did not match when: {}", type);
continue;
}
// exact match then break
if (clazz.equals(exception.getClass())) {
candidate = type;
candidateDiff = 0;
break;
}
// not an exact match so find the best candidate
int level = getInheritanceLevel(clazz);
int diff = targetLevel - level;
if (diff < candidateDiff) {
// replace with a much better candidate
candidate = type;
candidateDiff = diff;
}
}
}
if (candidate != null) {
if (!candidates.containsKey(candidateDiff)) {
// only add as candidate if we do not already have it registered with that level
LOG.trace("Adding {} as candidate at level {}", candidate, candidateDiff);
candidates.put(candidateDiff, candidate);
} else {
// for example we check route scope before context scope (preferring route scopes)
if (LOG.isTraceEnabled()) {
LOG.trace("Existing candidate {} takes precedence over{} at level {}", new Object[] { candidates.get(candidateDiff), candidate, candidateDiff });
}
}
}
// if we found a exact match then we should stop continue looking
boolean exactMatch = candidateDiff == 0;
if (LOG.isTraceEnabled() && exactMatch) {
LOG.trace("Exact match found for candidate: {}", candidate);
}
return exactMatch;
}
use of java.util.Map in project camel by apache.
the class RestBindingAdvice method unmarshal.
private void unmarshal(Exchange exchange, Map<String, Object> state) throws Exception {
boolean isXml = false;
boolean isJson = false;
String contentType = ExchangeHelper.getContentType(exchange);
if (contentType != null) {
isXml = contentType.toLowerCase(Locale.ENGLISH).contains("xml");
isJson = contentType.toLowerCase(Locale.ENGLISH).contains("json");
}
// that information in the consumes
if (!isXml && !isJson) {
isXml = consumes != null && consumes.toLowerCase(Locale.ENGLISH).contains("xml");
isJson = consumes != null && consumes.toLowerCase(Locale.ENGLISH).contains("json");
}
if (exchange.getIn() instanceof DataTypeAware && (isJson || isXml)) {
((DataTypeAware) exchange.getIn()).setDataType(new DataType(isJson ? "json" : "xml"));
}
// only allow xml/json if the binding mode allows that
isXml &= bindingMode.equals("auto") || bindingMode.contains("xml");
isJson &= bindingMode.equals("auto") || bindingMode.contains("json");
// if we do not yet know if its xml or json, then use the binding mode to know the mode
if (!isJson && !isXml) {
isXml = bindingMode.equals("auto") || bindingMode.contains("xml");
isJson = bindingMode.equals("auto") || bindingMode.contains("json");
}
state.put(STATE_KEY_ACCEPT, exchange.getIn().getHeader("Accept", String.class));
String body = null;
if (exchange.getIn().getBody() != null) {
// as they assume a non-empty body
if (isXml || isJson) {
// we have binding enabled, so we need to know if there body is empty or not
// so force reading the body as a String which we can work with
body = MessageHelper.extractBodyAsString(exchange.getIn());
if (body != null) {
if (exchange.getIn() instanceof DataTypeAware) {
((DataTypeAware) exchange.getIn()).setBody(body, new DataType(isJson ? "json" : "xml"));
} else {
exchange.getIn().setBody(body);
}
if (isXml && isJson) {
// we have still not determined between xml or json, so check the body if its xml based or not
isXml = body.startsWith("<");
isJson = !isXml;
}
}
}
}
// add missing default values which are mapped as headers
if (queryDefaultValues != null) {
for (Map.Entry<String, String> entry : queryDefaultValues.entrySet()) {
if (exchange.getIn().getHeader(entry.getKey()) == null) {
exchange.getIn().setHeader(entry.getKey(), entry.getValue());
}
}
}
// favor json over xml
if (isJson && jsonUnmarshal != null) {
// add reverse operation
state.put(STATE_KEY_DO_MARSHAL, STATE_JSON);
if (ObjectHelper.isNotEmpty(body)) {
jsonUnmarshal.process(exchange);
ExchangeHelper.prepareOutToIn(exchange);
}
return;
} else if (isXml && xmlUnmarshal != null) {
// add reverse operation
state.put(STATE_KEY_DO_MARSHAL, STATE_XML);
if (ObjectHelper.isNotEmpty(body)) {
xmlUnmarshal.process(exchange);
ExchangeHelper.prepareOutToIn(exchange);
}
return;
}
// we could not bind
if ("off".equals(bindingMode) || bindingMode.equals("auto")) {
// okay for auto we do not mind if we could not bind
state.put(STATE_KEY_DO_MARSHAL, STATE_JSON);
} else {
if (bindingMode.contains("xml")) {
exchange.setException(new BindingException("Cannot bind to xml as message body is not xml compatible", exchange));
} else {
exchange.setException(new BindingException("Cannot bind to json as message body is not json compatible", exchange));
}
}
}
Aggregations