Skip to content

Commit 5cd9064

Browse files
committed
feat: add compilation to jar file
1 parent 8efd85a commit 5cd9064

File tree

11 files changed

+241
-33
lines changed

11 files changed

+241
-33
lines changed

src/main/java/es/nachobrito/jsonschema/compiler/application/cli/RuntimeConfiguration.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public Optional<String> getPackageName() {
5959
}
6060

6161
@Override
62-
public Path getOutputFolder() {
62+
public Path getOutputPath() {
6363
return Path.of(arguments.getOrDefault(OUTPUT, "."));
6464
}
6565

src/main/java/es/nachobrito/jsonschema/compiler/domain/Compiler.java

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,22 @@
2323
import es.nachobrito.jsonschema.compiler.domain.generator.ModelGenerator;
2424
import es.nachobrito.jsonschema.compiler.domain.runtimeconfiguration.RuntimeConfiguration;
2525
import es.nachobrito.jsonschema.compiler.domain.schemareader.SchemaReaderFactory;
26-
import java.io.IOException;
2726
import java.lang.classfile.ClassBuilder;
2827
import java.lang.classfile.ClassFile;
2928
import java.net.URI;
30-
import java.nio.file.Path;
3129
import java.util.List;
3230
import java.util.SortedMap;
3331

3432
public class Compiler {
3533
private final RuntimeConfiguration runtimeConfiguration;
3634
private final SchemaReaderFactory schemaReaderFactory;
35+
private final GeneratedClassesHandler generatedClassesHandler;
3736

38-
public Compiler(RuntimeConfiguration runtimeConfiguration, SchemaReaderFactory schemaReaderFactory) {
37+
public Compiler(
38+
RuntimeConfiguration runtimeConfiguration, SchemaReaderFactory schemaReaderFactory) {
3939
this.runtimeConfiguration = runtimeConfiguration;
4040
this.schemaReaderFactory = schemaReaderFactory;
41+
this.generatedClassesHandler = runtimeConfiguration.getGeneratedClassesHandler();
4142
}
4243

4344
/**
@@ -58,9 +59,10 @@ public void compile(String jsonSchema) {
5859
compileAll(schemaReaderFactory.makeSchemaReader().read(jsonSchema));
5960
}
6061

61-
6262
private void compileAll(List<Schema> schemas) {
63+
generatedClassesHandler.beforeCompile();
6364
schemas.forEach(this::compileSchema);
65+
generatedClassesHandler.afterCompile();
6466
}
6567

6668
private void compileSchema(Schema schema) {
@@ -69,25 +71,13 @@ private void compileSchema(Schema schema) {
6971
.getPackageName()
7072
.map(pkg -> "%s.%s".formatted(pkg, schema.className()))
7173
.orElse(schema.className());
72-
var destinationPath = buildDestinationPath(className);
7374
var properties = schema.properties();
7475

75-
try {
76-
ClassFile.of()
77-
.buildTo(
78-
destinationPath,
79-
of(className),
80-
classBuilder -> writeRecord(className, classBuilder, properties));
81-
} catch (IOException e) {
82-
throw new CompilerException(e);
83-
}
84-
}
76+
var bytes =
77+
ClassFile.of()
78+
.build(of(className), classBuilder -> writeRecord(className, classBuilder, properties));
8579

86-
private Path buildDestinationPath(String className) {
87-
var parts = "%s.class".formatted(className.replace('.', '/'));
88-
var path = Path.of(runtimeConfiguration.getOutputFolder().toAbsolutePath().toString(), parts);
89-
path.getParent().toFile().mkdirs();
90-
return path;
80+
generatedClassesHandler.handleGeneratedClass(className, bytes);
9181
}
9282

9383
private void writeRecord(
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Copyright 2024 Nacho Brito
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package es.nachobrito.jsonschema.compiler.domain;
18+
19+
public interface GeneratedClassesHandler {
20+
21+
22+
default void beforeCompile(){
23+
//Implement this method for preparatory tasks before any class is generated.
24+
};
25+
26+
void handleGeneratedClass(String className, byte[] bytes);
27+
28+
default void afterCompile(){
29+
//Implement this method for resource cleanup after all classes have been compiled.
30+
}
31+
}

src/main/java/es/nachobrito/jsonschema/compiler/domain/runtimeconfiguration/RuntimeConfiguration.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616

1717
package es.nachobrito.jsonschema.compiler.domain.runtimeconfiguration;
1818

19+
import es.nachobrito.jsonschema.compiler.domain.GeneratedClassesHandler;
20+
import es.nachobrito.jsonschema.compiler.infrastructure.IndividualFilesHandler;
21+
import es.nachobrito.jsonschema.compiler.infrastructure.JarFileHandler;
1922
import java.nio.file.Path;
2023
import java.util.Optional;
2124

@@ -30,7 +33,7 @@ default Optional<String> getPackageName() {
3033
/**
3134
* @return the output folder for generated class files
3235
*/
33-
default Path getOutputFolder() {
36+
default Path getOutputPath() {
3437
return Path.of(".");
3538
}
3639

@@ -45,4 +48,12 @@ default Optional<String> getJsonSchemaCode() {
4548
default boolean withJacksonAnnotations() {
4649
return true;
4750
}
51+
52+
default GeneratedClassesHandler getGeneratedClassesHandler(){
53+
var path = getOutputPath().toAbsolutePath();
54+
if (path.toString().endsWith(".jar")) {
55+
return new JarFileHandler(path);
56+
}
57+
return new IndividualFilesHandler(path);
58+
}
4859
}

src/main/java/es/nachobrito/jsonschema/compiler/domain/runtimeconfiguration/RuntimeConfigurationRecord.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public Optional<String> getPackageName() {
2929
}
3030

3131
@Override
32-
public Path getOutputFolder() {
32+
public Path getOutputPath() {
3333
return destPath;
3434
}
3535
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
* Copyright 2024 Nacho Brito
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package es.nachobrito.jsonschema.compiler.infrastructure;
18+
19+
import es.nachobrito.jsonschema.compiler.domain.CompilerException;
20+
import es.nachobrito.jsonschema.compiler.domain.GeneratedClassesHandler;
21+
22+
import java.io.IOException;
23+
import java.nio.file.Files;
24+
import java.nio.file.Path;
25+
26+
public class IndividualFilesHandler implements GeneratedClassesHandler {
27+
28+
29+
private final Path outputFolder;
30+
31+
public IndividualFilesHandler(Path outputFolder) {
32+
this.outputFolder = outputFolder;
33+
}
34+
35+
@Override
36+
public void beforeCompile() {
37+
outputFolder.toFile().mkdirs();
38+
}
39+
40+
@Override
41+
public void handleGeneratedClass(String className, byte[] classBytes) {
42+
var destinationPath = buildDestinationPath(className);
43+
try {
44+
Files.write(destinationPath, classBytes);
45+
} catch (IOException e) {
46+
throw new CompilerException(e);
47+
}
48+
}
49+
50+
private Path buildDestinationPath(String className) {
51+
var parts = "%s.class".formatted(className.replace('.', '/'));
52+
return Path.of(outputFolder.toString(), parts);
53+
}
54+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
* Copyright 2024 Nacho Brito
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package es.nachobrito.jsonschema.compiler.infrastructure;
18+
19+
import es.nachobrito.jsonschema.compiler.domain.CompilerException;
20+
import es.nachobrito.jsonschema.compiler.domain.GeneratedClassesHandler;
21+
22+
import java.io.BufferedOutputStream;
23+
import java.io.IOException;
24+
import java.nio.file.Files;
25+
import java.nio.file.Path;
26+
import java.util.ArrayList;
27+
import java.util.List;
28+
import java.util.jar.JarEntry;
29+
import java.util.jar.JarOutputStream;
30+
import java.util.jar.Manifest;
31+
32+
import static java.util.jar.Attributes.Name.MANIFEST_VERSION;
33+
34+
public class JarFileHandler implements GeneratedClassesHandler {
35+
private final Path jarFilePath;
36+
37+
private record Entry(String name, byte[] bytes) {}
38+
39+
private List<Entry> entries = new ArrayList<>();
40+
41+
public JarFileHandler(Path jarFilePath) {
42+
this.jarFilePath = jarFilePath;
43+
}
44+
45+
@Override
46+
public void beforeCompile() {
47+
if (Files.exists(jarFilePath)) {
48+
throw new CompilerException(
49+
"Cannot overwrite existing Jar file! -> %s".formatted(jarFilePath.toString()));
50+
}
51+
}
52+
53+
@Override
54+
public void afterCompile() {
55+
var manifest = new Manifest();
56+
manifest.getMainAttributes().put(MANIFEST_VERSION, "1.0");
57+
try (var os =
58+
new JarOutputStream(
59+
new BufferedOutputStream(Files.newOutputStream(jarFilePath)), manifest)) {
60+
for (Entry entry : entries) {
61+
os.putNextEntry(new JarEntry(entry.name()));
62+
os.write(entry.bytes());
63+
os.closeEntry();
64+
}
65+
} catch (IOException e) {
66+
throw new CompilerException(e);
67+
}
68+
}
69+
70+
@Override
71+
public void handleGeneratedClass(String className, byte[] bytes) {
72+
var name = "%s.class".formatted(className.replace('.', '/'));
73+
entries.add(new Entry(name, bytes));
74+
}
75+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* Copyright 2024 Nacho Brito
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package es.nachobrito.jsonschema.compiler;
18+
19+
import org.junit.jupiter.api.DisplayName;
20+
import org.junit.jupiter.api.Test;
21+
22+
import java.io.IOException;
23+
import java.nio.file.Files;
24+
25+
import static org.junit.jupiter.api.Assertions.assertTrue;
26+
27+
public class CompileToJarTest extends CompilerTest{
28+
29+
@DisplayName("When the output path is a jar file, the generated classes have to be packed in it.")
30+
@Test
31+
void expectJarFilesGenerated() throws IOException, ClassNotFoundException {
32+
var jar = compileSampleSchemaFromFileToJar("classpath:test-schemas/Nested.json", "com.example");
33+
assertTrue(Files.exists(jar));
34+
}
35+
36+
}

src/test/java/es/nachobrito/jsonschema/compiler/CompilerSmokeTest.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
/** Verifies basic schema compilation, and general cases for toString/hashCode/equals methods. */
2929
public class CompilerSmokeTest extends CompilerTest{
3030

31-
public static final String TARGET_GENERATED_CLASSES = "target/generated-classes";
3231

3332
@Test
3433
void expectSimpleFileCompiled()

src/test/java/es/nachobrito/jsonschema/compiler/CompilerTest.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
import org.junit.jupiter.api.BeforeEach;
3838

3939
public class CompilerTest {
40+
public static final String TARGET_GENERATED_CLASSES = "target/generated-classes";
4041

4142
protected static Object instantiateSampleSchema(
4243
String filePath, String expectedName, Object... initArgs)
@@ -58,7 +59,7 @@ protected static Class<?> compileSampleSchemaFromFile(String filePath, String ex
5859
var compiler =
5960
new Compiler(new RuntimeConfigurationRecord(destPath, ""), new JsonSchemaReaderFactory());
6061
compiler.compile(uri);
61-
assertTrue(destPath.toFile().exists());
62+
assertTrue(Files.exists(destPath));
6263

6364
return new URLClassLoader(new URL[] {destURL}).loadClass(expectedName);
6465
}
@@ -70,7 +71,7 @@ protected static Class<?> compileSampleSchemaFromString(String jsonSchema, Strin
7071
var compiler =
7172
new Compiler(new RuntimeConfigurationRecord(destPath, ""), new JsonSchemaReaderFactory());
7273
compiler.compile(jsonSchema);
73-
assertTrue(destPath.toFile().exists());
74+
assertTrue(Files.exists(destPath));
7475

7576
return new URLClassLoader(new URL[] {destURL}).loadClass(expectedName);
7677
}
@@ -92,4 +93,15 @@ void afterAll() throws IOException {
9293
protected ObjectMapper createObjectMapper() {
9394
return new ObjectMapper().registerModule(new JavaTimeModule());
9495
}
96+
97+
98+
protected Path compileSampleSchemaFromFileToJar(String schemaFile, String packageName) {
99+
var uri = URI.create(schemaFile);
100+
Path destPath = Path.of(CompilerSmokeTest.TARGET_GENERATED_CLASSES + "/generated.jar");
101+
var compiler =
102+
new Compiler(new RuntimeConfigurationRecord(destPath, packageName), new JsonSchemaReaderFactory());
103+
compiler.compile(uri);
104+
assertTrue(Files.exists(destPath));
105+
return destPath;
106+
}
95107
}

0 commit comments

Comments
 (0)