Skip to content

Commit 4e251e3

Browse files
committed
Merge remote-tracking branch 'origin/JAVA-45628_1' into JAVA-45628_1
2 parents d9de22c + 909e1bb commit 4e251e3

File tree

1,268 files changed

+13876
-7952
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

1,268 files changed

+13876
-7952
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.algorithms.consecutivenumbers;
2+
3+
import org.junit.jupiter.api.Test;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
public class ConsecutiveNumbersUnitTest {
7+
8+
@Test
9+
void whenIsSumOfConsecutiveUsingBruteForce_thenReturnsTrue() {
10+
int n = 15;
11+
12+
boolean isSumOfConsecutive = false;
13+
for (int k = 2; (k * (k - 1)) / 2 < n; k++) {
14+
int diff = n - k * (k - 1) / 2;
15+
if (diff % k == 0 && diff / k > 0) {
16+
isSumOfConsecutive = true;
17+
break;
18+
}
19+
}
20+
21+
assertTrue(isSumOfConsecutive);
22+
}
23+
24+
@Test
25+
void whenIsSumOfConsecutiveUsingBitwise_thenReturnsTrue() {
26+
int n = 15;
27+
boolean result = (n > 0) && ((n & (n - 1)) != 0);
28+
assertTrue(result);
29+
}
30+
31+
}

apache-libraries-3/pom.xml

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
<artifactId>apache-libraries-3</artifactId>
77
<version>0.0.1-SNAPSHOT</version>
88
<name>apache-libraries-3</name>
9-
10-
119
<parent>
1210
<groupId>com.baeldung</groupId>
1311
<artifactId>parent-modules</artifactId>
@@ -44,6 +42,36 @@
4442
<artifactId>jackson-dataformat-avro</artifactId>
4543
<version>${jackson.version}</version>
4644
</dependency>
45+
<dependency>
46+
<groupId>org.apache.camel</groupId>
47+
<artifactId>camel-jackson</artifactId>
48+
<version>${camel.version}</version>
49+
</dependency>
50+
<dependency>
51+
<groupId>com.graphql-java</groupId>
52+
<artifactId>graphql-java</artifactId>
53+
<version>${graphql.version}</version>
54+
</dependency>
55+
<dependency>
56+
<groupId>org.apache.camel</groupId>
57+
<artifactId>camel-core</artifactId>
58+
<version>${camel.version}</version>
59+
</dependency>
60+
<dependency>
61+
<groupId>org.apache.camel</groupId>
62+
<artifactId>camel-jetty</artifactId>
63+
<version>${camel.version}</version>
64+
</dependency>
65+
<dependency>
66+
<groupId>org.apache.camel</groupId>
67+
<artifactId>camel-http</artifactId>
68+
<version>${camel.version}</version>
69+
</dependency>
70+
<dependency>
71+
<groupId>org.apache.camel</groupId>
72+
<artifactId>camel-graphql</artifactId>
73+
<version>${camel.version}</version>
74+
</dependency>
4775

4876
</dependencies>
4977

@@ -53,6 +81,8 @@
5381
<maven.compiler.target>17</maven.compiler.target>
5482
<avro.version>1.11.3</avro.version>
5583
<json-unit-assertj.version>3.5.0</json-unit-assertj.version>
84+
<graphql.version>23.1</graphql.version>
85+
<camel.version>4.11.0</camel.version>
5686
</properties>
5787

5888
</project>
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.apache.camel;
2+
3+
public class Book {
4+
5+
private String id;
6+
private String title;
7+
private String author;
8+
9+
public String getId() {
10+
return id;
11+
}
12+
13+
public void setId(String id) {
14+
this.id = id;
15+
}
16+
17+
public String getTitle() {
18+
return title;
19+
}
20+
21+
public void setTitle(String title) {
22+
this.title = title;
23+
}
24+
25+
public String getAuthor() {
26+
return author;
27+
}
28+
29+
public void setAuthor(String author) {
30+
this.author = author;
31+
}
32+
33+
public Book(String id, String title, String author) {
34+
this.id = id;
35+
this.title = title;
36+
this.author = author;
37+
}
38+
39+
public Book() {
40+
}
41+
}
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package com.baeldung.apache.camel;
2+
3+
import java.io.ByteArrayOutputStream;
4+
import java.io.IOException;
5+
import java.nio.charset.StandardCharsets;
6+
import java.util.Map;
7+
8+
import org.apache.camel.Exchange;
9+
import org.apache.camel.builder.RouteBuilder;
10+
import org.apache.camel.component.jackson.JacksonDataFormat;
11+
import org.apache.camel.converter.stream.InputStreamCache;
12+
import org.apache.camel.model.dataformat.JsonLibrary;
13+
import org.apache.camel.model.rest.RestBindingMode;
14+
import org.apache.camel.spi.RestConfiguration;
15+
16+
import com.fasterxml.jackson.core.JsonParseException;
17+
import com.fasterxml.jackson.databind.ObjectMapper;
18+
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
19+
20+
import graphql.ExecutionInput;
21+
import graphql.ExecutionResult;
22+
import graphql.GraphQL;
23+
import graphql.schema.GraphQLSchema;
24+
25+
public class BookRoute extends RouteBuilder {
26+
27+
private final BookService bookService = new BookService();
28+
29+
@Override
30+
public void configure() throws Exception {
31+
JacksonDataFormat jsonDataFormat = new JacksonDataFormat(Map.class);
32+
jsonDataFormat.setUnmarshalType(Object.class);
33+
34+
onException(Exception.class).handled(true)
35+
.setHeader("Content-Type", constant("application/json"))
36+
.setBody(simple("{\"error\": \"${exception.message}\"}"));
37+
38+
onException(IllegalArgumentException.class)
39+
.handled(true)
40+
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
41+
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
42+
.setBody(simple("{\"error\": \"${exception.message}\"}"));
43+
44+
onException(JsonParseException.class)
45+
.handled(true)
46+
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
47+
.setBody(simple("{\"error\": \"Invalid JSON: ${exception.message}\"}"));
48+
49+
restConfiguration().component("jetty")
50+
.host("localhost")
51+
.port(8088)
52+
.contextPath("/api")
53+
.bindingMode(RestBindingMode.json)
54+
.dataFormatProperty("prettyPrint", "true");
55+
56+
rest("/books")
57+
.get().to("direct:getAllBooks")
58+
.get("/{id}").to("direct:getBookById")
59+
.post()
60+
.consumes("application/json")
61+
.type(Book.class)
62+
.to("direct:addBook");
63+
64+
from("direct:getAllBooks").bean(bookService, "getBooks");
65+
from("direct:getBookById").bean(bookService, "getBookById(${header.id})");
66+
from("direct:addBook").bean(bookService, "addBook");
67+
68+
GraphQLSchema schema = new CustomSchemaLoader().loadSchema();
69+
GraphQL graphQL = GraphQL.newGraphQL(schema).build();
70+
71+
from("jetty:http://localhost:8088/graphql?matchOnUriPrefix=true")
72+
.log("Received GraphQL request: ${body}")
73+
.convertBodyTo(String.class)
74+
.process(exchange -> {
75+
String body = exchange.getIn().getBody(String.class);
76+
try {
77+
Map<String, Object> payload = new ObjectMapper().readValue(body, Map.class);
78+
String query = (String) payload.get("query");
79+
if (query == null || query.trim().isEmpty()) {
80+
throw new IllegalArgumentException("Missing 'query' field in request body");
81+
}
82+
ExecutionInput executionInput = ExecutionInput.newExecutionInput()
83+
.query(query)
84+
.build();
85+
ExecutionResult result = graphQL.execute(executionInput);
86+
Map<String, Object> response = result.toSpecification();
87+
exchange.getIn().setBody(response);
88+
} catch (Exception e) {
89+
throw new RuntimeException("GraphQL processing error", e);
90+
}
91+
})
92+
.marshal().json(JsonLibrary.Jackson)
93+
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"));
94+
}
95+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.apache.camel;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class BookService {
7+
8+
private final List<Book> books = new ArrayList<>();
9+
10+
public BookService() {
11+
books.add(new Book("1", "Clean Code", "Robert"));
12+
books.add(new Book("2", "Effective Java", "Joshua"));
13+
}
14+
15+
public List<Book> getBooks() {
16+
return books;
17+
}
18+
19+
public Book getBookById(String id) {
20+
return books.stream()
21+
.filter(b -> b.getId()
22+
.equals(id))
23+
.findFirst()
24+
.orElse(null);
25+
}
26+
27+
public Book addBook(Book book) {
28+
books.add(book);
29+
return book;
30+
}
31+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.baeldung.apache.camel;
2+
3+
import org.apache.camel.CamelContext;
4+
import org.apache.camel.impl.DefaultCamelContext;
5+
import org.slf4j.Logger;
6+
import org.slf4j.LoggerFactory;
7+
8+
import graphql.GraphQL;
9+
import graphql.schema.GraphQLSchema;
10+
11+
public class CamelRestGraphQLApp {
12+
private static final Logger logger = LoggerFactory.getLogger(CamelRestGraphQLApp.class);
13+
public static void main(String[] args) throws Exception {
14+
CamelContext context = new DefaultCamelContext();
15+
context.addRoutes(new BookRoute());
16+
context.start();
17+
logger.info("Server running at http://localhost:8088");
18+
Thread.sleep(Long.MAX_VALUE);
19+
context.stop();
20+
}
21+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.baeldung.apache.camel;
2+
3+
import java.io.InputStream;
4+
import java.io.InputStreamReader;
5+
import org.slf4j.Logger;
6+
import org.slf4j.LoggerFactory;
7+
import graphql.schema.GraphQLSchema;
8+
import graphql.schema.idl.RuntimeWiring;
9+
import graphql.schema.idl.SchemaGenerator;
10+
import graphql.schema.idl.SchemaParser;
11+
import graphql.schema.idl.TypeDefinitionRegistry;
12+
13+
public class CustomSchemaLoader {
14+
15+
private static final Logger logger = LoggerFactory.getLogger(CustomSchemaLoader.class);
16+
private final BookService bookService = new BookService();
17+
18+
public GraphQLSchema loadSchema() {
19+
logger.debug("Attempting to load schema");
20+
try (InputStream schemaStream = getClass().getClassLoader().getResourceAsStream("books.graphql")) {
21+
if (schemaStream == null) {
22+
throw new RuntimeException("GraphQL schema file 'books.graphql' not found in classpath");
23+
}
24+
logger.debug("Schema file found. Parsing...");
25+
TypeDefinitionRegistry registry = new SchemaParser()
26+
.parse(new InputStreamReader(schemaStream));
27+
28+
RuntimeWiring wiring = buildRuntimeWiring();
29+
30+
return new SchemaGenerator().makeExecutableSchema(registry, wiring);
31+
32+
} catch (Exception e) {
33+
logger.error("Failed to load GraphQL schema", e);
34+
throw new RuntimeException("GraphQL schema initialization failed", e);
35+
}
36+
}
37+
38+
private RuntimeWiring buildRuntimeWiring() {
39+
return RuntimeWiring.newRuntimeWiring()
40+
.type("Query", builder -> builder
41+
.dataFetcher("books", env -> bookService.getBooks())
42+
.dataFetcher("bookById", env -> bookService.getBookById(env.getArgument("id"))))
43+
.type("Mutation", builder -> builder
44+
.dataFetcher("addBook", env -> {
45+
String id = env.getArgument("id");
46+
String title = env.getArgument("title");
47+
String author = env.getArgument("author");
48+
if (title == null || title.isEmpty()) {
49+
throw new IllegalArgumentException("Title cannot be empty");
50+
}
51+
return bookService.addBook(new Book(id, title, author));
52+
}))
53+
.build();
54+
}
55+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
type Book {
2+
id: String!
3+
title: String!
4+
author: String
5+
}
6+
7+
type Query {
8+
books: [Book]
9+
bookById(id: String!): Book
10+
}
11+
12+
type Mutation {
13+
addBook(id: String!, title: String!, author: String): Book
14+
}

0 commit comments

Comments
 (0)