Debian Codegraph @

curator-examples/src/main/java/modeled/ModeledCuratorExamples.java

raw
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package modeled;
21
22 import java.util.function.Consumer;
23 import org.apache.curator.x.async.AsyncCuratorFramework;
24 import org.apache.curator.x.async.modeled.JacksonModelSerializer;
25 import org.apache.curator.x.async.modeled.ModelSpec;
26 import org.apache.curator.x.async.modeled.ModeledFramework;
27 import org.apache.curator.x.async.modeled.ZPath;
28
29 public class ModeledCuratorExamples {
30 public static ModeledFramework<PersonModel> wrap(AsyncCuratorFramework client) {
31 JacksonModelSerializer<PersonModel> serializer = JacksonModelSerializer.build(PersonModel.class);
32
33 // build a model specification - you can pre-build all the model specifications for your app at startup
34 ModelSpec<PersonModel> modelSpec =
35 ModelSpec.builder(ZPath.parse("/example/path"), serializer).build();
36
37 // wrap a CuratorFramework instance so that it can be used "modeled".
38 // do this once and re-use the returned ModeledFramework instance.
39 // ModeledFramework instances are tied to a given path
40 return ModeledFramework.wrap(client, modelSpec);
41 }
42
43 public static void createOrUpdate(ModeledFramework<PersonModel> modeled, PersonModel model) {
44 // change the affected path to be modeled's base path plus id: i.e. "/example/path/{id}"
45 ModeledFramework<PersonModel> atId = modeled.child(model.getId().getId());
46
47 // by default ModeledFramework instances update the node if it already exists
48 // so this will either create or update the node
49 atId.set(model); // note - this is async
50 }
51
52 public static void readPerson(ModeledFramework<PersonModel> modeled, String id, Consumer<PersonModel> receiver) {
53 // read the person with the given ID and asynchronously call the receiver after it is read
54 modeled.child(id).read().whenComplete((person, exception) -> {
55 if (exception != null) {
56 exception.printStackTrace(); // handle the error
57 } else {
58 receiver.accept(person);
59 }
60 });
61 }
62 }