001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.component.rest;
018
019import java.util.Map;
020import java.util.Set;
021
022import org.apache.camel.Component;
023import org.apache.camel.Consumer;
024import org.apache.camel.ExchangePattern;
025import org.apache.camel.NoFactoryAvailableException;
026import org.apache.camel.NoSuchBeanException;
027import org.apache.camel.Processor;
028import org.apache.camel.Producer;
029import org.apache.camel.impl.DefaultEndpoint;
030import org.apache.camel.spi.FactoryFinder;
031import org.apache.camel.spi.Metadata;
032import org.apache.camel.spi.RestApiConsumerFactory;
033import org.apache.camel.spi.RestApiProcessorFactory;
034import org.apache.camel.spi.RestConfiguration;
035import org.apache.camel.spi.UriEndpoint;
036import org.apache.camel.spi.UriParam;
037import org.apache.camel.spi.UriPath;
038import org.apache.camel.util.HostUtils;
039import org.apache.camel.util.ObjectHelper;
040
041/**
042 * The rest-api component is used for providing Swagger API of the REST services which has been defined using the rest-dsl in Camel.
043 */
044@UriEndpoint(scheme = "rest-api", title = "REST API", syntax = "rest-api:path/contextIdPattern", consumerOnly = true, label = "core,rest", lenientProperties = true)
045public class RestApiEndpoint extends DefaultEndpoint {
046
047    public static final String DEFAULT_API_COMPONENT_NAME = "swagger";
048    public static final String RESOURCE_PATH = "META-INF/services/org/apache/camel/rest/";
049
050    @UriPath
051    @Metadata(required = "true")
052    private String path;
053    @UriPath
054    private String contextIdPattern;
055    @UriParam
056    private String componentName;
057    @UriParam
058    private String apiComponentName;
059
060    private Map<String, Object> parameters;
061
062    public RestApiEndpoint(String endpointUri, RestApiComponent component) {
063        super(endpointUri, component);
064        setExchangePattern(ExchangePattern.InOut);
065    }
066
067    @Override
068    public RestApiComponent getComponent() {
069        return (RestApiComponent) super.getComponent();
070    }
071
072    public String getPath() {
073        return path;
074    }
075
076    /**
077     * The base path
078     */
079    public void setPath(String path) {
080        this.path = path;
081    }
082
083    public String getContextIdPattern() {
084        return contextIdPattern;
085    }
086
087    /**
088     * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern.
089     */
090    public void setContextIdPattern(String contextIdPattern) {
091        this.contextIdPattern = contextIdPattern;
092    }
093
094    public String getComponentName() {
095        return componentName;
096    }
097
098    /**
099     * The Camel Rest component to use for the REST transport, such as restlet, spark-rest.
100     * If no component has been explicit configured, then Camel will lookup if there is a Camel component
101     * that integrates with the Rest DSL, or if a org.apache.camel.spi.RestConsumerFactory is registered in the registry.
102     * If either one is found, then that is being used.
103     */
104    public void setComponentName(String componentName) {
105        this.componentName = componentName;
106    }
107
108    public String getApiComponentName() {
109        return apiComponentName;
110    }
111
112    /**
113     * The Camel Rest API component to use for generating the API of the REST services, such as swagger.
114     */
115    public void setApiComponentName(String apiComponentName) {
116        this.apiComponentName = apiComponentName;
117    }
118
119    public Map<String, Object> getParameters() {
120        return parameters;
121    }
122
123    /**
124     * Additional parameters to configure the consumer of the REST transport for this REST service
125     */
126    public void setParameters(Map<String, Object> parameters) {
127        this.parameters = parameters;
128    }
129
130    @Override
131    public Producer createProducer() throws Exception {
132        RestApiProcessorFactory factory = null;
133
134        RestConfiguration config = getCamelContext().getRestConfiguration(componentName, true);
135
136        // lookup in registry
137        Set<RestApiProcessorFactory> factories = getCamelContext().getRegistry().findByType(RestApiProcessorFactory.class);
138        if (factories != null && factories.size() == 1) {
139            factory = factories.iterator().next();
140        }
141
142        // lookup on classpath using factory finder to automatic find it (just add camel-swagger-java to classpath etc)
143        if (factory == null) {
144            String name = apiComponentName != null ? apiComponentName : config.getApiComponent();
145            if (name == null) {
146                name = DEFAULT_API_COMPONENT_NAME;
147            }
148            try {
149                FactoryFinder finder = getCamelContext().getFactoryFinder(RESOURCE_PATH);
150                Object instance = finder.newInstance(name);
151                if (instance instanceof RestApiProcessorFactory) {
152                    factory = (RestApiProcessorFactory) instance;
153                }
154            } catch (NoFactoryAvailableException e) {
155                // ignore
156            }
157        }
158
159        if (factory != null) {
160
161            // if no explicit port/host configured, then use port from rest configuration
162            String host = "";
163            int port = 80;
164
165            if (config.getHost() != null) {
166                host = config.getHost();
167            }
168            int num = config.getPort();
169            if (num > 0) {
170                port = num;
171            }
172
173            // if no explicit hostname set then resolve the hostname
174            if (ObjectHelper.isEmpty(host)) {
175                if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
176                    host = HostUtils.getLocalHostName();
177                } else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
178                    host = HostUtils.getLocalIp();
179                }
180
181                // no host was configured so calculate a host to use
182                // there should be no schema in the host (but only port)
183                String targetHost = host + (port != 80 ? ":" + port : "");
184                getParameters().put("host", targetHost);
185            }
186
187            // the base path should start with a leading slash
188            String path = getPath();
189            if (path != null && !path.startsWith("/")) {
190                path = "/" + path;
191            }
192
193            // whether listing of the context id's is enabled or not
194            boolean contextIdListing = config.isApiContextListing();
195
196            Processor processor = factory.createApiProcessor(getCamelContext(), path, getContextIdPattern(), contextIdListing, config, getParameters());
197            return new RestApiProducer(this, processor);
198        } else {
199            throw new IllegalStateException("Cannot find RestApiProcessorFactory in Registry or classpath (such as the camel-swagger-java component)");
200        }
201    }
202
203    @Override
204    public Consumer createConsumer(Processor processor) throws Exception {
205        RestApiConsumerFactory factory = null;
206        String cname = null;
207
208        // we use the rest component as the HTTP consumer to service the API
209        // the API then uses the api component (eg usually camel-swagger-java) to build the API
210        if (getComponentName() != null) {
211            Object comp = getCamelContext().getRegistry().lookupByName(getComponentName());
212            if (comp != null && comp instanceof RestApiConsumerFactory) {
213                factory = (RestApiConsumerFactory) comp;
214            } else {
215                comp = getCamelContext().getComponent(getComponentName());
216                if (comp != null && comp instanceof RestApiConsumerFactory) {
217                    factory = (RestApiConsumerFactory) comp;
218                }
219            }
220
221            if (factory == null) {
222                if (comp != null) {
223                    throw new IllegalArgumentException("Component " + getComponentName() + " is not a RestApiConsumerFactory");
224                } else {
225                    throw new NoSuchBeanException(getComponentName(), RestApiConsumerFactory.class.getName());
226                }
227            }
228            cname = getComponentName();
229        }
230
231        // try all components
232        if (factory == null) {
233            for (String name : getCamelContext().getComponentNames()) {
234                Component comp = getCamelContext().getComponent(name);
235                if (comp != null && comp instanceof RestApiConsumerFactory) {
236                    factory = (RestApiConsumerFactory) comp;
237                    cname = name;
238                    break;
239                }
240            }
241        }
242
243        // lookup in registry
244        if (factory == null) {
245            Set<RestApiConsumerFactory> factories = getCamelContext().getRegistry().findByType(RestApiConsumerFactory.class);
246            if (factories != null && factories.size() == 1) {
247                factory = factories.iterator().next();
248            }
249        }
250
251        if (factory != null) {
252            // calculate the url to the rest API service
253            RestConfiguration config = getCamelContext().getRestConfiguration(cname, true);
254
255            // calculate the url to the rest API service
256            String path = getPath();
257            if (path != null && !path.startsWith("/")) {
258                path = "/" + path;
259            }
260
261            Consumer consumer = factory.createApiConsumer(getCamelContext(), processor, path, config, getParameters());
262            configureConsumer(consumer);
263
264            return consumer;
265        } else {
266            throw new IllegalStateException("Cannot find RestApiConsumerFactory in Registry or as a Component to use");
267        }
268    }
269
270    @Override
271    public boolean isSingleton() {
272        return true;
273    }
274
275    @Override
276    public boolean isLenientProperties() {
277        return true;
278    }
279}