org.apache.camel.model.rest.RestBindingMode Java Examples

The following examples show how to use org.apache.camel.model.rest.RestBindingMode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OrderRoute.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {

    // configure rest-dsl
    restConfiguration()
       // to use spark-rest component and run on port 8080
        .component("spark-rest").port(8080)
        // and enable json binding mode
        .bindingMode(RestBindingMode.json)
        // lets enable pretty printing json responses
        .dataFormatProperty("prettyPrint", "true");

    // rest services under the orders context-path
    rest("/orders")
        // need to specify the POJO types the binding is using (otherwise json binding defaults to Map based)
        .get("{id}").outType(Order.class)
            .to("bean:orderService?method=getOrder(${header.id})")
            // need to specify the POJO types the binding is using (otherwise json binding defaults to Map based)
        .post().type(Order.class)
            .to("bean:orderService?method=createOrder")
            // need to specify the POJO types the binding is using (otherwise json binding defaults to Map based)
        .put().type(Order.class)
            .to("bean:orderService?method=updateOrder")
        .delete("{id}")
            .to("bean:orderService?method=cancelOrder(${header.id})");
}
 
Example #2
Source File: UndertowSecureRestDslCdiRoutes4.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {

    restConfiguration()
        .host("localhost")
        .port(8080)
        .component("undertow")
        .contextPath("/api")
        .apiProperty("api.title", "WildFly Camel REST API")
        .apiProperty("api.version", "1.0")
        .apiContextPath("swagger");
    ;

    rest()
        .get("/endpoint1")
            .bindingMode(RestBindingMode.auto)
            .id("endpoint1")
            .description("A test endpoint1")
            .outType(String.class)
            .route()
               .setBody(constant("GET: /api/endpoint1"))
            .endRest()
    ;

}
 
Example #3
Source File: OrderRoute.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    // configure rest to use netty4-http component as the HTTP server component
    // enable json binding mode so we can leverage camel-jackson to bind json to/from pojos
    restConfiguration().component("netty4-http").bindingMode(RestBindingMode.json)
            // expose the service as localhost:8080/service
            .host("localhost").port(8080).contextPath("service");

    // include a token id header, which we insert before the consumer completes
    // (and therefore before the consumer writes the response to the caller)
    onCompletion().modeBeforeConsumer()
            .setHeader("Token").method("tokenService");

    // use rest-dsl to define the rest service to lookup orders
    rest()
        .get("/order/{id}")
            .to("bean:orderService?method=getOrder");

}
 
Example #4
Source File: ApplicationTest.java    From kubernetes-integration-test with Apache License 2.0 6 votes vote down vote up
@Bean
public RouteBuilder addTestHttpService() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            //See ServletMappingConfiguration mapping properties: camel.component.servlet.mapping
            restConfiguration().component("servlet") //Requires "CamelServlet" to be registered
                .bindingMode(RestBindingMode.off);

            rest("address")
                .produces(MediaType.APPLICATION_JSON_VALUE)
                .get("email/{email}")
                    .route().routeId("test-http")
                    .setBody().constant("{\"address\":\"1428 Elm Street\"}")
                    .to("mock:addressByEmail")
                    .endRest();
        }
    };
}
 
Example #5
Source File: CustomerCamelRoute.java    From istio-tutorial with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    restConfiguration()
            .component("servlet")
            .enableCORS(true)
            .contextPath("/")
            .bindingMode(RestBindingMode.auto);

    rest("/").get().consumes(MediaType.TEXT_PLAIN_VALUE)
            .route().routeId("root")
            .pipeline()
                .bean("CustomerCamelRoute", "addTracer")
                .to("http4:preference:8080/?httpClient.connectTimeout=1000&bridgeEndpoint=true&copyHeaders=true&connectionClose=true")
            .end()
            .convertBodyTo(String.class)
            .onException(HttpOperationFailedException.class)
                .handled(true)
                .process(this::handleHttpFailure)
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(503))
            .end()
            .onException(Exception.class)
                .log(exceptionMessage().toString())
                .handled(true)
                .transform(simpleF(RESPONSE_STRING_FORMAT, exceptionMessage()))
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(503))
            .end()
            .transform(simpleF(RESPONSE_STRING_FORMAT, "${body}"))
    .endRest();
}
 
Example #6
Source File: CafeRoute.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    restConfiguration()
        .component("undertow").port(port1)
        .bindingMode(RestBindingMode.json);

    rest("/cafe/menu")
        .get("/items").outType(MenuItem[].class)
            .to("bean:menuService?method=getMenuItems")
        .get("/items/{id}").outType(MenuItem.class)
            .to("bean:menuService?method=getMenuItem(${header.id})")
        .post("/items").type(MenuItem.class)
            .route().to("bean:menuService?method=createMenuItem").setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201)).endRest()
        .put("/items/{id}").type(MenuItem.class)
            .to("bean:menuService?method=updateMenuItem(${header.id}, ${body})")
        .delete("/items/{id}")
           .to("bean:menuService?method=removeMenuItem(${header.id})");
}
 
Example #7
Source File: PreferenceCamelRoute.java    From istio-tutorial with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    restConfiguration()
            .component("servlet")
            .enableCORS(true)
            .contextPath("/")
            .bindingMode(RestBindingMode.auto);

    rest("/").get().produces("text/plain")
            .route().routeId("root")
            .to("http4:recommendation:8080/?httpClient.connectTimeout=1000&bridgeEndpoint=true&copyHeaders=true&connectionClose=true")
            .routeId("recommendation")
            .onException(HttpOperationFailedException.class)
                .handled(true)
                .process(this::handleHttpFailure)
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(503))
                .end()
            .onException(Exception.class)
                .handled(true)
                .transform(simpleF(RESPONSE_STRING_FORMAT, exceptionMessage()) )
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(503))
                .end()
            .transform(simpleF(RESPONSE_STRING_FORMAT, "${body}"))
            .endRest();
}
 
Example #8
Source File: RestAPIRouteBuilder.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
public void configure() throws Exception {
    restConfiguration()
        .contextPath("/rest/api")
        .apiContextPath("/api-doc")
        .apiProperty("api.title", "Camel REST API")
        .apiProperty("api.version", "1.0")
        .apiProperty("cors", "true")
        .apiContextRouteId("doc-api")
        .component("undertow")
        .bindingMode(RestBindingMode.json);

    rest("/books").description("Books REST service")
        .get("/").description("The list of all the books")
            .route()
                .toF("jpa:%s?nativeQuery=select distinct description from orders", Order.class.getName())
            .endRest()
        .get("order/{id}").description("Details of an order by id")
            .route()
                .toF("jpa:%s?consumeDelete=false&parameters=#queryParameters&nativeQuery=select * from orders where id = :id", Order.class.getName())
                .process("jpaResultProcessor")
            .endRest();
}
 
Example #9
Source File: CartRoute.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {

    // use jetty for rest service
    restConfiguration("jetty").port("{{port}}").contextPath("api")
            // turn on json binding
            .bindingMode(RestBindingMode.json)
            // turn off binding error on empty beans
            .dataFormatProperty("disableFeatures", "FAIL_ON_EMPTY_BEANS")
            // enable swagger api documentation
            .apiContextPath("api-doc")
            .enableCORS(true);

    // define the rest service
    rest("/cart").consumes("application/json").produces("application/json")
        // get returns List<CartDto>
        .get().outTypeList(CartDto.class).description("Returns the items currently in the shopping cart")
            .to("bean:cart?method=getItems")
        // get accepts CartDto
        .post().type(CartDto.class).description("Adds the item to the shopping cart")
            .to("bean:cart?method=addItem")
        .delete().description("Removes the item from the shopping cart")
            .param().name("itemId").description("Id of item to remove").endParam()
            .to("bean:cart?method=removeItem");
}
 
Example #10
Source File: CartRoute.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {

    // use jetty for rest service
    restConfiguration("jetty").port("{{port}}").contextPath("api")
            // turn on json binding
            .bindingMode(RestBindingMode.json)
            // turn off binding error on empty beans
            .dataFormatProperty("disableFeatures", "FAIL_ON_EMPTY_BEANS")
            // enable swagger api documentation
            .apiContextPath("api-doc")
            .enableCORS(true);

    // define the rest service
    rest("/cart").consumes("application/json").produces("application/json")
        // get returns List<CartDto>
        .get().outType(CartDto[].class).description("Returns the items currently in the shopping cart")
            .to("bean:cart?method=getItems")
        // get accepts CartDto
        .post().type(CartDto.class).description("Adds the item to the shopping cart")
            .to("bean:cart?method=addItem")
        .delete().description("Removes the item from the shopping cart")
            .param().name("itemId").description("Id of item to remove").endParam()
            .to("bean:cart?method=removeItem");
}
 
Example #11
Source File: CafeApiRoute.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    onException(MenuItemNotFoundException.class)
        .handled(true)
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(404))
        .setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
        .setBody().simple("${exception.message}");

    onException(MenuItemInvalidException.class)
        .handled(true)
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
        .setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
        .setBody().simple("${exception.message}");

    onException(JsonParseException.class)
        .handled(true)
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
        .setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
        .setBody().constant("Invalid json data");

    restConfiguration()
        .component("undertow").port(port1)
        .bindingMode(RestBindingMode.json)
        .apiContextPath("api-doc")
        .apiProperty("api.title", "Cafe Menu")
        .apiProperty("api.version", "1.0.0")
        .apiProperty("api.description", "Cafe Menu Sample API")
        .apiProperty("api.contact.name", "Camel Cookbook")
        .apiProperty("api.contact.url", "http://www.camelcookbook.org")
        .apiProperty("api.license.name", "Apache 2.0")
        .apiProperty("api.license.url", "http://www.apache.org/licenses/LICENSE-2.0.html")
        .enableCORS(true);

    rest("/cafe/menu").description("Cafe Menu Services")
        .get("/items").description("Returns all menu items").outType(MenuItem[].class)
            .responseMessage().code(200).message("All of the menu items").endResponseMessage()
            .to("bean:menuService?method=getMenuItems")
        .get("/items/{id}").description("Returns menu item with matching id").outType(MenuItem.class)
            .param().name("id").type(RestParamType.path).description("The id of the item").dataType("int").endParam()
            .responseMessage().code(200).message("The requested menu item").endResponseMessage()
            .responseMessage().code(404).message("Menu item not found").endResponseMessage()
            .to("bean:menuService?method=getMenuItem(${header.id})")
        .post("/items").description("Creates a new menu item").type(MenuItem.class)
            .param().name("body").type(RestParamType.body).description("The item to create").endParam()
            .responseMessage().code(201).message("Successfully created menu item").endResponseMessage()
            .responseMessage().code(400).message("Invalid menu item").endResponseMessage()
            .route().to("bean:menuService?method=createMenuItem").setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201)).endRest()
        .put("/items/{id}").description("Updates an existing or creates a new menu item").type(MenuItem.class)
            .param().name("id").type(RestParamType.path).description("The id of the item").dataType("int").endParam()
            .param().name("body").type(RestParamType.body).description("The menu item new contents").endParam()
            .responseMessage().code(200).message("Successfully updated item").endResponseMessage()
            .responseMessage().code(400).message("Invalid menu item").endResponseMessage()
            .to("bean:menuService?method=updateMenuItem(${header.id}, ${body})")
        .delete("/items/{id}").description("Deletes the specified item")
            .param().name("id").type(RestParamType.path).description("The id of the item").dataType("int").endParam()
            .responseMessage().code(200).message("Successfully deleted item").endResponseMessage()
            .to("bean:menuService?method=removeMenuItem(${header.id})");
}
 
Example #12
Source File: CamelRoutes.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    restConfiguration().component("servlet").bindingMode(RestBindingMode.auto);

    rest()
        .get("/greetings/{name}").produces("text/plain")
            .route().transform(simple("Hello ${header.name}"));
}
 
Example #13
Source File: CamelRoutes.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {

    restConfiguration().component("undertow")
        .contextPath("/rest").bindingMode(RestBindingMode.auto);

    rest()
        .get("/greetings/{name}").produces("text/plain")
            .route().transform(simple("Hello ${header.name} from " + name));
}
 
Example #14
Source File: CamelRoutes.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    restConfiguration().component("undertow")
            .port(8080)
            .bindingMode(RestBindingMode.auto);

    rest()
            .get("/greetings/{name}").produces("text/plain")
            .route().transform(simple("Hello ${header.name}"));

}
 
Example #15
Source File: CafeErrorRoute.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    restConfiguration()
        .component("undertow").port(port1)
        .bindingMode(RestBindingMode.json);

    // TODO: add exception handler for Invalid Item

    onException(MenuItemNotFoundException.class)
        .handled(true)
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(404))
        .setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
        .setBody().simple("${exception.message}");

    onException(MenuItemInvalidException.class)
        .handled(true)
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
        .setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
        .setBody().simple("${exception.message}");

    onException(JsonParseException.class)
        .handled(true)
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
        .setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
        .setBody().constant("Invalid json data");

    rest("/cafe/menu")
        .get("/items").outType(MenuItem[].class)
            .to("bean:menuService?method=getMenuItems")
        .get("/items/{id}").outType(MenuItem.class)
            .to("bean:menuService?method=getMenuItem(${header.id})")
        .post("/items").type(MenuItem.class)
            .route().to("bean:menuService?method=createMenuItem").setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201)).endRest()
        .put("/items/{id}").type(MenuItem.class)
            .to("bean:menuService?method=updateMenuItem(${header.id}, ${body})")
        .delete("/items/{id}")
            .to("bean:menuService?method=removeMenuItem(${header.id})");
}
 
Example #16
Source File: RestRouteBuilder.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {

    restConfiguration()
        .host("localhost")
        .port(8080)
        .component("undertow")
        .contextPath("/api")
        .apiProperty("api.title", "WildFly Camel REST API")
        .apiProperty("api.version", "1.0")
        .apiContextPath("swagger");

    rest("/customers").description("Customers REST service")
        .get("/{id}")
            .bindingMode(RestBindingMode.auto)
            .id("getCustomerById")
            .description("Retrieves a customer for the specified id")
            .outType(Customer.class)
            .route()
                .process(exchange -> {
                    Customer customer = new Customer();
                    customer.setId(exchange.getIn().getHeader("id", Integer.class));
                    customer.setFirstName("Kermit");
                    customer.setLastName("The Frog");
                    exchange.getMessage().setBody(customer);
                })
            .endRest();
}
 
Example #17
Source File: BindingModeRoute.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    restConfiguration()
        .component("undertow").port(port1).bindingMode(RestBindingMode.json_xml);

    rest()
        .get("/items").outType(Item[].class).to("bean:itemService?method=getItems")
        .get("/items/{id}").outType(Item.class).to("bean:itemService?method=getItem(${header.id})")
        .get("/items/{id}/xml").outType(Item.class).bindingMode(RestBindingMode.xml).to("bean:itemService?method=getItem(${header.id})")
        .get("/items/{id}/json").outType(Item.class).bindingMode(RestBindingMode.json).to("bean:itemService?method=getItem(${header.id})")
        .put("/items/{id}").type(Item.class).to("bean:itemService?method=setItem(${header.id}, ${body})");
}
 
Example #18
Source File: RestBindingModeXmlRoute.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() {
    rest()
            .post("/platform-http/nameOf")
            .bindingMode(RestBindingMode.xml)
            .type(UserJaxbPojo.class)
            .route()
            .transform().body(UserJaxbPojo.class, UserJaxbPojo::getName);
}
 
Example #19
Source File: RatingRoute.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    // notice that we have also configured rest in the application.properties file
    restConfiguration()
        // turn on json binding in rest-dsl
        .bindingMode(RestBindingMode.json);

    // define the rest service
    rest("/ratings/{ids}").produces("application/json")
        .get().to("bean:ratingService");
}
 
Example #20
Source File: RatingRoute.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    // notice that we have also configured rest in the application.properties file
    restConfiguration()
        // turn on json binding in rest-dsl
        .bindingMode(RestBindingMode.json);

    // define the rest service
    rest("/ratings/{ids}").produces("application/json")
        .get().to("bean:ratingService");
}
 
Example #21
Source File: ClientCamelVmSedaITest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@Override
public RouteBuilder getRouteBuilder() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            restConfiguration().component("restlet").host("localhost").
                    port(8180).bindingMode(RestBindingMode.auto);

            rest("/orders")
                    .get("/createOrder").to("direct:createOrder");

            from("direct:createOrder")
                    .to("seda:checkStock")
                    .choice()
                    .when(body().isEqualTo(true))
                    .to("direct:processOrder")
                    .otherwise()
                    .transform().constant("Order NOT created: Out of Stock");

            from("direct:processOrder")
                    .to("vm:checkCredit")
                    .choice()
                    .when(body().isEqualTo(true))
                    .transform().constant(ORDER_CREATED).endChoice()
                    .otherwise()
                    .transform().constant("Order NOT created: Insufficient Credit");

            from("seda:checkStock")
                    .transform().constant(true);

            from("vm:checkCredit")
                    .transform().constant(true);
        }
    };
}
 
Example #22
Source File: RestDslPostTest.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
public RouteBuilder route() {
    return new RouteBuilder() {
        public void configure() {
            restConfiguration().host("localhost").port(PORT).bindingMode(RestBindingMode.json);

            rest("/").post("/user").type(UserPojo.class).route().to("mock:user").endRest().post("/country")
                    .type(CountryPojo.class).route().to("mock:country").endRest();

        }
    };
}
 
Example #23
Source File: OrderRoute.java    From camelinaction2 with Apache License 2.0 4 votes vote down vote up
@Override
public void configure() throws Exception {

    // configure rest-dsl
    restConfiguration()
       // to use undertow component and run on port 8080
        .component("undertow").port(8080)
        // and enable json/xml binding mode
        .bindingMode(RestBindingMode.json_xml)
        // lets enable pretty printing json responses
        .dataFormatProperty("prettyPrint", "true")
        // lets enable swagger api
        .apiContextPath("api-doc")
        // and setup api properties
        .apiProperty("api.version", "2.0.0")
        .apiProperty("api.title", "Rider Auto Parts Order Services")
        .apiProperty("api.description", "Order Service that allows customers to submit orders and query status")
        .apiProperty("api.contact.name", "Rider Auto Parts");


    // error handling to return custom HTTP status codes for the various exceptions

    onException(OrderInvalidException.class)
        .handled(true)
        // use HTTP status 400 when input data is invalid
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
        .setBody(constant(""));

    onException(OrderNotFoundException.class)
        .handled(true)
        // use HTTP status 404 when data was not found
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(404))
        .setBody(constant(""));

    onException(Exception.class)
        .handled(true)
        // use HTTP status 500 when we had a server side error
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(500))
        .setBody(simple("${exception.message}\n"));

    // rest services under the orders context-path
    rest("/orders").description("Order services")

        .get("/ping").apiDocs(false)
            .to("direct:ping")

        .get("{id}").outType(Order.class)
            .description("Service to get details of an existing order")
            .param().name("id").description("The order id").endParam()
            .responseMessage().code(200).message("The order with the given id").endResponseMessage()
            .responseMessage().code(404).message("Order not found").endResponseMessage()
            .responseMessage().code(500).message("Server error").endResponseMessage()
            .to("bean:orderService?method=getOrder(${header.id})")

        .post().type(Order.class).outType(String.class)
            .description("Service to submit a new order")
            .responseMessage()
                .code(200).message("The created order id")
            .endResponseMessage()
            .responseMessage().code(400).message("Invalid input data").endResponseMessage()
            .responseMessage().code(500).message("Server error").endResponseMessage()
            .to("bean:orderService?method=createOrder")

        .put().type(Order.class)
            .description("Service to update an existing order")
            .responseMessage().code(400).message("Invalid input data").endResponseMessage()
            .responseMessage().code(500).message("Server error").endResponseMessage()
            .to("bean:orderService?method=updateOrder")

        .delete("{id}")
            .description("Service to cancel an existing order")
            .param().name("id").description("The order id").endParam()
            .responseMessage().code(404).message("Order not found").endResponseMessage()
            .responseMessage().code(500).message("Server error").endResponseMessage()
            .to("bean:orderService?method=cancelOrder(${header.id})");
}
 
Example #24
Source File: OrderRoute.java    From camelinaction2 with Apache License 2.0 4 votes vote down vote up
@Override
public void configure() throws Exception {

    // configure rest-dsl
    restConfiguration()
       // to use undertow component and run on port 8080
        .component("undertow").port(8080)
        // and enable json/xml binding mode
        .bindingMode(RestBindingMode.json_xml)
        // lets enable pretty printing json responses
        .dataFormatProperty("prettyPrint", "true");

    // error handling to return custom HTTP status codes for the various exceptions

    onException(OrderInvalidException.class)
        .handled(true)
        // use HTTP status 400 when input data is invalid
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
        .setBody(constant(""));

    onException(OrderNotFoundException.class)
        .handled(true)
        // use HTTP status 404 when data was not found
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(404))
        .setBody(constant(""));

    onException(Exception.class)
        .handled(true)
        // use HTTP status 500 when we had a server side error
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(500))
        .setBody(simple("${exception.message}\n"));

    // rest services under the orders context-path
    rest("/orders")
        // need to specify the POJO types the binding is using (otherwise json binding defaults to Map based)
        .get("{id}").outType(Order.class)
            .to("bean:orderService?method=getOrder(${header.id})")
            // need to specify the POJO types the binding is using (otherwise json binding defaults to Map based)
        .post().type(Order.class)
            .to("bean:orderService?method=createOrder")
            // need to specify the POJO types the binding is using (otherwise json binding defaults to Map based)
        .put().type(Order.class)
            .to("bean:orderService?method=updateOrder")
        .delete("{id}")
            .to("bean:orderService?method=cancelOrder(${header.id})");
}
 
Example #25
Source File: ClientCamelRestletITest.java    From hawkular-apm with Apache License 2.0 4 votes vote down vote up
@Override
public RouteBuilder getRouteBuilder() {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            restConfiguration().component("restlet").host("localhost").
                    port(8180).bindingMode(RestBindingMode.auto);

            rest("/orders")
                    .get("/createOrder").to("direct:createOrder");

            rest("/inventory")
                    .get("/checkStock").to("seda:checkStock");

            rest("/creditagency")
                    .get("/checkCredit").to("vm:checkCredit");

            from("direct:createOrder")
                    .to("language:simple:" + URLEncoder.encode("Hello", "UTF-8"))
                    .to("restlet:http://localhost:8180/inventory/checkStock")
                    .choice()
                    .when(body().isEqualTo(true))
                    .to("direct:processOrder")
                    .otherwise()
                    .transform().constant("Order NOT created: Out of Stock");

            from("direct:processOrder")
                    .to("restlet:http://localhost:8180/creditagency/checkCredit")
                    .choice()
                    .when(body().isEqualTo(true))
                    .transform().constant(ORDER_CREATED).endChoice()
                    .otherwise()
                    .transform().constant("Order NOT created: Insufficient Credit");

            from("seda:checkStock")
                    .transform().constant(true);

            from("vm:checkCredit")
                    .transform().constant(true);
        }
    };
}
 
Example #26
Source File: RestRouteBuilder.java    From wildfly-camel-examples with Apache License 2.0 4 votes vote down vote up
public void configure() throws Exception {

        /**
         * Configure an error handler to trap instances where the data posted to
         * the REST API is invalid
         */
        onException(JsonParseException.class)
            .handled(true)
            .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
            .setHeader(Exchange.CONTENT_TYPE, constant(MediaType.TEXT_PLAIN))
            .setBody().constant("Invalid json data");

        /**
         * Configure Camel REST to use the camel-undertow component
         */
        restConfiguration()
            .bindingMode(RestBindingMode.json)
            .component("undertow")
            .contextPath("rest/api")
            .host("localhost")
            .port(8080)
            .enableCORS(true)
            .apiProperty("api.title", "WildFly Camel REST API")
            .apiProperty("api.version", "1.0")
            .apiContextPath("swagger");

        /**
         * Configure REST API with a base path of /customers
         */
        rest("/customers").description("Customers REST service")
            .get()
                .description("Retrieves all customers")
                .produces(MediaType.APPLICATION_JSON)
                .route()
                    .bean(CustomerService.class, "findAll")
                .endRest()

            .get("/{id}")
                .description("Retrieves a customer for the specified id")
                .param()
                    .name("id")
                    .description("Customer ID")
                    .type(RestParamType.path)
                    .dataType("int")
                .endParam()
                .produces(MediaType.APPLICATION_JSON)
                .route()
                    .bean(CustomerService.class, "findById")
                .endRest()

            .post()
                .description("Creates a new customer")
                .consumes(MediaType.APPLICATION_JSON)
                .produces(MediaType.APPLICATION_JSON)
                .type(Customer.class)
                .route()
                    .bean(CustomerService.class, "create")
                .endRest()

            .put("/{id}")
                .description("Updates the customer relating to the specified id")
                .param()
                    .name("id")
                    .description("Customer ID")
                    .type(RestParamType.path)
                    .dataType("int")
                .endParam()
                .consumes(MediaType.APPLICATION_JSON)
                .type(Customer.class)
                .route()
                    .bean(CustomerService.class, "update")
                .endRest()

            .delete("/{id}")
                .description("Deletes the customer relating to the specified id")
                .param()
                    .name("id")
                    .description("Customer ID")
                    .type(RestParamType.path)
                    .dataType("int")
                .endParam()
                .route()
                    .bean(CustomerService.class, "delete")
                .endRest();
    }
 
Example #27
Source File: RecommendationCamelRoute.java    From istio-tutorial with Apache License 2.0 4 votes vote down vote up
@Override
    public void configure() throws Exception {
        restConfiguration()
                .component("servlet")
                .enableCORS(true)
                .contextPath("/")
                .bindingMode(RestBindingMode.auto);

        rest("/").get().produces("text/plain")
                .route().routeId("root")
//                .to("direct:timeout")
                .choice()
                    .when(method("RecommendationCamelRoute", "isMisbehave"))
                        .to("direct:misbehave")
                    .otherwise()
                        .to("direct:response")
                .endChoice()
        .endRest();

        rest("/misbehave").get().produces("text/plain")
                .route().routeId("misbehave")
                .process(exchange -> {
                    this.misbehave = true;
                    log.info("'misbehave' has been set to 'true'");
                    exchange.getOut().setBody("Following requests to '/' will return a 503\n");
                })
        .endRest();


        rest("/behave").get().produces("text/plain")
                .route().routeId("behave")
                .process(exchange -> {
                    this.misbehave = false;
                    log.info("'misbehave' has been set to 'false'");
                    exchange.getOut().setBody("Following requests to '/' will return a 200\n");
                })
        .endRest();

        from("direct:response")
                .process(exchange -> {
                   count++;
                   log.info(String.format("recommendation request from %s: %d", HOSTNAME, count));
                   exchange.getOut().setBody(String.format(RESPONSE_STRING_FORMAT, HOSTNAME, count));
                }).end();

        from("direct:misbehave")
                .log(String.format("Misbehaving %d", count))
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(503))
                .transform(simpleF("recommendation misbehavior from '%s'\\n", HOSTNAME))
                .process(exchange -> {
                    count = 0;
                }).end();

        from("direct:timeout")
                .process(exchange -> {Thread.sleep(3000);}).end();
    }
 
Example #28
Source File: Application.java    From tutorials with MIT License 4 votes vote down vote up
@Override
        public void configure() {

            CamelContext context = new DefaultCamelContext();

            
            // http://localhost:8080/camel/api-doc
            restConfiguration().contextPath(contextPath) //
                .port(serverPort)
                .enableCORS(true)
                .apiContextPath("/api-doc")
                .apiProperty("api.title", "Test REST API")
                .apiProperty("api.version", "v1")
                .apiProperty("cors", "true") // cross-site
                .apiContextRouteId("doc-api")
                .component("servlet")
                .bindingMode(RestBindingMode.json)
                .dataFormatProperty("prettyPrint", "true");
/** 
The Rest DSL supports automatic binding json/xml contents to/from 
POJOs using Camels Data Format.
By default the binding mode is off, meaning there is no automatic 
binding happening for incoming and outgoing messages.
You may want to use binding if you develop POJOs that maps to 
your REST services request and response types. 
*/         
            
            rest("/api/").description("Teste REST Service")
                .id("api-route")
                .post("/bean")
                .produces(MediaType.APPLICATION_JSON)
                .consumes(MediaType.APPLICATION_JSON)
//                .get("/hello/{place}")
                .bindingMode(RestBindingMode.auto)
                .type(MyBean.class)
                .enableCORS(true)
//                .outType(OutBean.class)

                .to("direct:remoteService");
            
       
            from("direct:remoteService")
                .routeId("direct-route")
                .tracing()
                .log(">>> ${body.id}")
                .log(">>> ${body.name}")
//                .transform().simple("blue ${in.body.name}")                
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        MyBean bodyIn = (MyBean) exchange.getIn().getBody();
                        
                        ExampleServices.example(bodyIn);

                        exchange.getIn().setBody(bodyIn);
                    }
                })
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201));
        }
 
Example #29
Source File: RestConfigurationDefinitionProperties.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
public void setBindingMode(RestBindingMode bindingMode) {
    this.bindingMode = bindingMode;
}
 
Example #30
Source File: RestConfigurationDefinitionProperties.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
public RestBindingMode getBindingMode() {
    return bindingMode;
}