|
| 1 | +/* |
| 2 | + * Copyright 2021 Google LLC |
| 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 pubsub; |
| 18 | + |
| 19 | +// [START pubsub_create_avro_schema] |
| 20 | + |
| 21 | +import com.google.api.gax.rpc.AlreadyExistsException; |
| 22 | +import com.google.cloud.pubsub.v1.SchemaServiceClient; |
| 23 | +import com.google.pubsub.v1.ProjectName; |
| 24 | +import com.google.pubsub.v1.Schema; |
| 25 | +import com.google.pubsub.v1.SchemaName; |
| 26 | +import java.io.IOException; |
| 27 | +import java.nio.file.Files; |
| 28 | +import java.nio.file.Paths; |
| 29 | + |
| 30 | +public class CreateAvroSchemaExample { |
| 31 | + |
| 32 | + public static void main(String... args) throws Exception { |
| 33 | + // TODO(developer): Replace these variables before running the sample. |
| 34 | + String projectId = "your-project-id"; |
| 35 | + String schemaId = "your-schema-id"; |
| 36 | + String avscFile = "path/to/an/avro/schema/file/(.avsc)/formatted/in/json"; |
| 37 | + |
| 38 | + createAvroSchemaExample(projectId, schemaId, avscFile); |
| 39 | + } |
| 40 | + |
| 41 | + public static void createAvroSchemaExample(String projectId, String schemaId, String avscFile) |
| 42 | + throws IOException { |
| 43 | + |
| 44 | + ProjectName projectName = ProjectName.of(projectId); |
| 45 | + SchemaName schemaName = SchemaName.of(projectId, schemaId); |
| 46 | + |
| 47 | + // Read an Avro schema file formatted in JSON as a string. |
| 48 | + String avscSource = new String(Files.readAllBytes(Paths.get(avscFile))); |
| 49 | + |
| 50 | + try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) { |
| 51 | + |
| 52 | + Schema schema = |
| 53 | + schemaServiceClient.createSchema( |
| 54 | + projectName, |
| 55 | + Schema.newBuilder() |
| 56 | + .setName(schemaName.toString()) |
| 57 | + .setType(com.google.pubsub.v1.Schema.Type.AVRO) |
| 58 | + .setDefinition(avscSource) |
| 59 | + .build(), |
| 60 | + schemaId); |
| 61 | + |
| 62 | + System.out.println("Created a schema using an Avro schema:\n" + schema); |
| 63 | + } catch (AlreadyExistsException e) { |
| 64 | + System.out.println(schemaName + "already exists."); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | +// [END pubsub_create_avro_schema] |
0 commit comments