1 package io.apicurio.registry.maven;
2
3 import com.fasterxml.jackson.databind.JsonNode;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import com.google.protobuf.Descriptors.FileDescriptor;
6 import io.apicurio.registry.content.ContentHandle;
7 import io.apicurio.registry.content.TypedContent;
8 import io.apicurio.registry.content.refs.ExternalReference;
9 import io.apicurio.registry.content.refs.ReferenceFinder;
10 import io.apicurio.registry.maven.refs.IndexedResource;
11 import io.apicurio.registry.maven.refs.ReferenceIndex;
12 import io.apicurio.registry.rest.client.RegistryClient;
13 import io.apicurio.registry.rest.client.models.*;
14 import io.apicurio.registry.rules.ParsedJsonSchema;
15 import io.apicurio.registry.types.ArtifactType;
16 import io.apicurio.registry.types.ContentTypes;
17 import io.apicurio.registry.types.provider.ArtifactTypeUtilProvider;
18 import io.apicurio.registry.types.provider.DefaultArtifactTypeUtilProviderImpl;
19 import io.vertx.core.Vertx;
20 import org.apache.avro.Schema;
21 import org.apache.commons.io.FileUtils;
22 import org.apache.maven.plugin.MojoExecutionException;
23 import org.apache.maven.plugin.MojoFailureException;
24 import org.apache.maven.plugins.annotations.Mojo;
25 import org.apache.maven.plugins.annotations.Parameter;
26
27 import java.io.*;
28 import java.nio.charset.StandardCharsets;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.*;
33 import java.util.concurrent.ExecutionException;
34 import java.util.stream.Collectors;
35
36
37
38
39 @Mojo(name = "register")
40 public class RegisterRegistryMojo extends AbstractRegistryMojo {
41
42
43
44
45 @Parameter(required = false)
46 List<ExistingReference> existingReferences;
47
48
49
50
51 @Parameter(required = true)
52 List<RegisterArtifact> artifacts;
53
54
55
56
57 @Parameter(property = "skipRegister", defaultValue = "false")
58 boolean skip;
59
60
61
62
63
64 @Parameter(property = "dryRun", defaultValue = "false")
65 boolean dryRun;
66
67 DefaultArtifactTypeUtilProviderImpl utilProviderFactory = new DefaultArtifactTypeUtilProviderImpl();
68
69
70
71
72 protected boolean validate() throws MojoExecutionException {
73 if (skip) {
74 getLog().info("register is skipped.");
75 return false;
76 }
77
78 if (artifacts == null || artifacts.isEmpty()) {
79 getLog().warn("No artifacts are configured for registration.");
80 return false;
81 }
82
83 if (existingReferences == null) {
84 existingReferences = new ArrayList<>();
85 }
86
87 int idx = 0;
88 int errorCount = 0;
89 for (RegisterArtifact artifact : artifacts) {
90 if (artifact.getGroupId() == null) {
91 getLog().error(String.format(
92 "GroupId is required when registering an artifact. Missing from artifacts[%d].",
93 idx));
94 errorCount++;
95 }
96 if (artifact.getArtifactId() == null) {
97 getLog().error(String.format(
98 "ArtifactId is required when registering an artifact. Missing from artifacts[%s].",
99 idx));
100 errorCount++;
101 }
102 if (artifact.getFile() == null) {
103 getLog().error(String.format(
104 "File is required when registering an artifact. Missing from artifacts[%s].", idx));
105 errorCount++;
106 } else if (!artifact.getFile().exists()) {
107 getLog().error(
108 String.format("Artifact file to register is configured but file does not exist: %s",
109 artifact.getFile().getPath()));
110 errorCount++;
111 }
112
113 idx++;
114 }
115
116 if (errorCount > 0) {
117 throw new MojoExecutionException(
118 "Invalid configuration of the Register Artifact(s) mojo. See the output log for details.");
119 }
120 return true;
121 }
122
123 @Override
124 protected void executeInternal() throws MojoExecutionException {
125 int errorCount = 0;
126 if (validate()) {
127 Vertx vertx = createVertx();
128 RegistryClient registryClient = createClient(vertx);
129
130 for (RegisterArtifact artifact : artifacts) {
131 String groupId = artifact.getGroupId();
132 String artifactId = artifact.getArtifactId();
133 try {
134 if (artifact.getAutoRefs() != null && artifact.getAutoRefs()) {
135
136
137 ReferenceIndex index = createIndex(artifact.getFile());
138 addExistingReferencesToIndex(registryClient, index, existingReferences);
139 addExistingReferencesToIndex(registryClient, index, artifact.getExistingReferences());
140 Stack<RegisterArtifact> registrationStack = new Stack<>();
141
142 registerWithAutoRefs(registryClient, artifact, index, registrationStack);
143 } else if (artifact.getAnalyzeDirectory() != null && artifact.getAnalyzeDirectory()) {
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159 registerDirectory(registryClient, artifact);
160 } else {
161
162 List<ArtifactReference> references = new ArrayList<>();
163
164 if (hasReferences(artifact)) {
165 references = processArtifactReferences(registryClient, artifact.getReferences());
166 }
167 registerArtifact(registryClient, artifact, references);
168 }
169 } catch (Exception e) {
170 errorCount++;
171 getLog().error(String.format("Exception while registering artifact [%s] / [%s]", groupId,
172 artifactId), e);
173 }
174
175 }
176
177 if (errorCount > 0) {
178 throw new MojoExecutionException("Errors while registering artifacts ...");
179 }
180 }
181 }
182
183 private VersionMetaData registerWithAutoRefs(RegistryClient registryClient, RegisterArtifact artifact,
184 ReferenceIndex index, Stack<RegisterArtifact> registrationStack) throws IOException,
185 ExecutionException, InterruptedException, MojoExecutionException, MojoFailureException {
186 if (loopDetected(artifact, registrationStack)) {
187 throw new RuntimeException(
188 "Artifact reference loop detected (not supported): " + printLoop(registrationStack));
189 }
190 registrationStack.push(artifact);
191
192
193 ContentHandle artifactContent = readContent(artifact.getFile());
194 String artifactContentType = getContentTypeByExtension(artifact.getFile().getName());
195 TypedContent typedArtifactContent = TypedContent.create(artifactContent, artifactContentType);
196
197
198 ArtifactTypeUtilProvider provider = this.utilProviderFactory
199 .getArtifactTypeProvider(artifact.getArtifactType());
200 ReferenceFinder referenceFinder = provider.getReferenceFinder();
201 var referenceArtifactIdentifierExtractor = provider.getReferenceArtifactIdentifierExtractor();
202 Set<ExternalReference> externalReferences = referenceFinder
203 .findExternalReferences(typedArtifactContent);
204
205
206 List<ArtifactReference> registeredReferences = new ArrayList<>(externalReferences.size());
207 for (ExternalReference externalRef : externalReferences) {
208 IndexedResource iresource = index.lookup(externalRef.getResource(),
209 Paths.get(artifact.getFile().toURI()));
210
211
212 if (iresource == null) {
213 throw new RuntimeException("Reference could not be resolved. From: "
214 + artifact.getFile().getName() + " To: " + externalRef.getFullReference());
215 }
216
217
218 if (!iresource.isRegistered()) {
219
220 String artifactId = referenceArtifactIdentifierExtractor.extractArtifactId(externalRef.getResource());
221 String groupId = referenceArtifactIdentifierExtractor.extractGroupId(externalRef.getResource());
222 File localFile = getLocalFile(iresource.getPath());
223 RegisterArtifact refArtifact = buildFromRoot(artifact, artifactId, groupId);
224 refArtifact.setArtifactType(iresource.getType());
225 refArtifact.setVersion(null);
226 refArtifact.setFile(localFile);
227 refArtifact.setContentType(getContentTypeByExtension(localFile.getName()));
228 try {
229 var car = registerWithAutoRefs(registryClient, refArtifact, index, registrationStack);
230 iresource.setRegistration(car);
231 } catch (IOException | ExecutionException | InterruptedException e) {
232 throw new RuntimeException(e);
233 }
234 }
235
236 var reference = new ArtifactReference();
237 reference.setName(externalRef.getFullReference());
238 reference.setVersion(iresource.getRegistration().getVersion());
239 reference.setGroupId(iresource.getRegistration().getGroupId());
240 reference.setArtifactId(iresource.getRegistration().getArtifactId());
241 registeredReferences.add(reference);
242 }
243 registeredReferences.sort((ref1, ref2) -> ref1.getName().compareTo(ref2.getName()));
244
245 registrationStack.pop();
246 return registerArtifact(registryClient, artifact, registeredReferences);
247 }
248
249 private void registerDirectory(RegistryClient registryClient, RegisterArtifact artifact)
250 throws IOException, ExecutionException, InterruptedException, MojoExecutionException,
251 MojoFailureException {
252 switch (artifact.getArtifactType()) {
253 case ArtifactType.AVRO:
254 final AvroDirectoryParser avroDirectoryParser = new AvroDirectoryParser(registryClient);
255 final ParsedDirectoryWrapper<Schema> schema = avroDirectoryParser.parse(artifact.getFile());
256 registerArtifact(registryClient, artifact, avroDirectoryParser
257 .handleSchemaReferences(artifact, schema.getSchema(), schema.getSchemaContents()));
258 break;
259 case ArtifactType.PROTOBUF:
260 final ProtobufDirectoryParser protobufDirectoryParser = new ProtobufDirectoryParser(
261 registryClient);
262 final ParsedDirectoryWrapper<FileDescriptor> protoSchema = protobufDirectoryParser
263 .parse(artifact.getFile());
264 registerArtifact(registryClient, artifact, protobufDirectoryParser.handleSchemaReferences(
265 artifact, protoSchema.getSchema(), protoSchema.getSchemaContents()));
266 break;
267 case ArtifactType.JSON:
268 final JsonSchemaDirectoryParser jsonSchemaDirectoryParser = new JsonSchemaDirectoryParser(
269 registryClient);
270 final ParsedDirectoryWrapper<ParsedJsonSchema> jsonSchema = jsonSchemaDirectoryParser
271 .parse(artifact.getFile());
272 registerArtifact(registryClient, artifact, jsonSchemaDirectoryParser.handleSchemaReferences(
273 artifact, jsonSchema.getSchema(), jsonSchema.getSchemaContents()));
274 break;
275 default:
276 throw new IllegalArgumentException(
277 String.format("Artifact type not recognized for analyzing a directory structure %s",
278 artifact.getArtifactType()));
279 }
280 }
281
282 private VersionMetaData registerArtifact(RegistryClient registryClient, RegisterArtifact artifact,
283 List<ArtifactReference> references) throws FileNotFoundException, ExecutionException,
284 InterruptedException, MojoExecutionException, MojoFailureException {
285 if (artifact.getFile() != null) {
286 return registerArtifact(registryClient, artifact, new FileInputStream(artifact.getFile()),
287 references);
288 } else {
289 return getArtifactVersionMetadata(registryClient, artifact);
290 }
291 }
292
293 private VersionMetaData getArtifactVersionMetadata(RegistryClient registryClient,
294 RegisterArtifact artifact) {
295 String groupId = artifact.getGroupId();
296 String artifactId = artifact.getArtifactId();
297 String version = artifact.getVersion();
298
299 VersionMetaData amd = registryClient.groups().byGroupId(groupId).artifacts().byArtifactId(artifactId)
300 .versions().byVersionExpression(version).get();
301 getLog().info(String.format("Successfully processed artifact [%s] / [%s]. GlobalId is [%d]", groupId,
302 artifactId, amd.getGlobalId()));
303
304 return amd;
305 }
306
307 private VersionMetaData registerArtifact(RegistryClient registryClient, RegisterArtifact artifact,
308 InputStream artifactContent, List<ArtifactReference> references)
309 throws ExecutionException, InterruptedException, MojoFailureException, MojoExecutionException {
310 String groupId = artifact.getGroupId();
311 String artifactId = artifact.getArtifactId();
312 String version = artifact.getVersion();
313 String type = artifact.getArtifactType();
314 Boolean canonicalize = artifact.getCanonicalize();
315 String ct = artifact.getContentType() == null ? ContentTypes.APPLICATION_JSON
316 : artifact.getContentType();
317 String data = null;
318 try {
319 if (artifact.getMinify() != null && artifact.getMinify()) {
320 ObjectMapper objectMapper = new ObjectMapper();
321 JsonNode jsonNode = objectMapper.readValue(artifactContent, JsonNode.class);
322 data = jsonNode.toString();
323 } else {
324 data = new String(artifactContent.readAllBytes(), StandardCharsets.UTF_8);
325 }
326 } catch (IOException e) {
327 throw new RuntimeException(e);
328 }
329
330 CreateArtifact createArtifact = new CreateArtifact();
331 createArtifact.setArtifactId(artifactId);
332 createArtifact.setArtifactType(type);
333
334 CreateVersion createVersion = new CreateVersion();
335 createVersion.setVersion(version);
336 createArtifact.setFirstVersion(createVersion);
337
338 VersionContent content = new VersionContent();
339 content.setContent(data);
340 content.setContentType(ct);
341 content.setReferences(references.stream().map(r -> {
342 ArtifactReference ref = new ArtifactReference();
343 ref.setArtifactId(r.getArtifactId());
344 ref.setGroupId(r.getGroupId());
345 ref.setVersion(r.getVersion());
346 ref.setName(r.getName());
347 return ref;
348 }).collect(Collectors.toList()));
349 createVersion.setContent(content);
350
351 try {
352 var vmd = registryClient.groups().byGroupId(groupId).artifacts().post(createArtifact, config -> {
353 if (artifact.getIfExists() != null) {
354 config.queryParameters.ifExists = IfArtifactExists
355 .forValue(artifact.getIfExists().value());
356 if (dryRun) {
357 config.queryParameters.dryRun = true;
358 }
359 }
360 config.queryParameters.canonical = canonicalize;
361 });
362
363 getLog().info(String.format("Successfully registered artifact [%s] / [%s]. GlobalId is [%d]",
364 groupId, artifactId, vmd.getVersion().getGlobalId()));
365
366 return vmd.getVersion();
367 } catch (RuleViolationProblemDetails | ProblemDetails e) {
368 logAndThrow(e);
369 return null;
370 }
371 }
372
373 private static boolean hasReferences(RegisterArtifact artifact) {
374 return artifact.getReferences() != null && !artifact.getReferences().isEmpty();
375 }
376
377 private List<ArtifactReference> processArtifactReferences(RegistryClient registryClient,
378 List<RegisterArtifactReference> referencedArtifacts) throws FileNotFoundException,
379 ExecutionException, InterruptedException, MojoExecutionException, MojoFailureException {
380 List<ArtifactReference> references = new ArrayList<>();
381 for (RegisterArtifactReference artifact : referencedArtifacts) {
382 List<ArtifactReference> nestedReferences = new ArrayList<>();
383
384
385 if (hasReferences(artifact)) {
386 nestedReferences = processArtifactReferences(registryClient, artifact.getReferences());
387 }
388 final VersionMetaData artifactMetaData = registerArtifact(registryClient, artifact,
389 nestedReferences);
390 references.add(buildReferenceFromMetadata(artifactMetaData, artifact.getName()));
391 }
392 return references;
393 }
394
395 public void setArtifacts(List<RegisterArtifact> artifacts) {
396 this.artifacts = artifacts;
397 }
398
399 public void setSkip(boolean skip) {
400 this.skip = skip;
401 }
402
403 private static ArtifactReference buildReferenceFromMetadata(VersionMetaData metaData,
404 String referenceName) {
405 ArtifactReference reference = new ArtifactReference();
406 reference.setName(referenceName);
407 reference.setArtifactId(metaData.getArtifactId());
408 reference.setGroupId(metaData.getGroupId());
409 reference.setVersion(metaData.getVersion());
410 return reference;
411 }
412
413 private static boolean isFileAllowedInIndex(File file) {
414 return file.isFile() && (
415 file.getName().toLowerCase().endsWith(".json") ||
416 file.getName().toLowerCase().endsWith(".yml") ||
417 file.getName().toLowerCase().endsWith(".yaml") ||
418 file.getName().toLowerCase().endsWith(".xml") ||
419 file.getName().toLowerCase().endsWith(".xsd") ||
420 file.getName().toLowerCase().endsWith(".wsdl") ||
421 file.getName().toLowerCase().endsWith(".graphql") ||
422 file.getName().toLowerCase().endsWith(".avsc") ||
423 file.getName().toLowerCase().endsWith(".proto")
424 );
425 }
426
427
428
429
430
431
432 private static ReferenceIndex createIndex(File file) {
433 ReferenceIndex index = new ReferenceIndex(file.getParentFile().toPath());
434 Collection<File> allFiles = FileUtils.listFiles(file.getParentFile(), null, true);
435 allFiles.stream().filter(RegisterRegistryMojo::isFileAllowedInIndex).forEach(f -> {
436 index.index(f.toPath(), readContent(f));
437 });
438 return index;
439 }
440
441 private void addExistingReferencesToIndex(RegistryClient registryClient, ReferenceIndex index,
442 List<ExistingReference> existingReferences) throws ExecutionException, InterruptedException {
443 if (existingReferences != null && !existingReferences.isEmpty()) {
444 for (ExistingReference ref : existingReferences) {
445 VersionMetaData vmd;
446 if (ref.getVersion() == null || "LATEST".equalsIgnoreCase(ref.getVersion())) {
447 vmd = registryClient.groups().byGroupId(ref.getGroupId()).artifacts()
448 .byArtifactId(ref.getArtifactId()).versions().byVersionExpression("branch=latest")
449 .get();
450 } else {
451 vmd = new VersionMetaData();
452 vmd.setGroupId(ref.getGroupId());
453 vmd.setArtifactId(ref.getArtifactId());
454 vmd.setVersion(ref.getVersion());
455 }
456 index.index(ref.getResourceName(), vmd);
457 }
458 }
459 }
460
461 protected static ContentHandle readContent(File file) {
462 try {
463 return ContentHandle.create(Files.readAllBytes(file.toPath()));
464 } catch (IOException e) {
465 throw new RuntimeException("Failed to read schema file: " + file, e);
466 }
467 }
468
469 protected static RegisterArtifact buildFromRoot(RegisterArtifact rootArtifact, String artifactId, String groupId) {
470 RegisterArtifact nestedSchema = new RegisterArtifact();
471 nestedSchema.setCanonicalize(rootArtifact.getCanonicalize());
472 nestedSchema.setArtifactId(artifactId);
473 nestedSchema.setGroupId(groupId == null ? rootArtifact.getGroupId() : groupId);
474 nestedSchema.setContentType(rootArtifact.getContentType());
475 nestedSchema.setArtifactType(rootArtifact.getArtifactType());
476 nestedSchema.setMinify(rootArtifact.getMinify());
477 nestedSchema.setContentType(rootArtifact.getContentType());
478 nestedSchema.setIfExists(rootArtifact.getIfExists());
479 nestedSchema.setAutoRefs(rootArtifact.getAutoRefs());
480 return nestedSchema;
481 }
482
483 private static File getLocalFile(Path path) {
484 return path.toFile();
485 }
486
487
488
489
490
491
492
493 private static boolean loopDetected(RegisterArtifact artifact,
494 Stack<RegisterArtifact> registrationStack) {
495 for (RegisterArtifact stackArtifact : registrationStack) {
496 if (artifact.getFile().equals(stackArtifact.getFile())) {
497 return true;
498 }
499 }
500 return false;
501 }
502
503 private static String printLoop(Stack<RegisterArtifact> registrationStack) {
504 return registrationStack.stream().map(artifact -> artifact.getFile().getName())
505 .collect(Collectors.joining(" -> "));
506 }
507
508 }