180f7b8f45a698bc5e847cd020074a8ae28263bb
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / md / sal / binding / impl / BindingToNormalizedNodeCodecFactory.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.md.sal.binding.impl;
9
10 import java.util.concurrent.atomic.AtomicBoolean;
11 import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
12 import org.opendaylight.controller.sal.core.api.model.SchemaService;
13 import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
14 import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
15 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
16
17 /**
18  * Factory class for creating and initializing the global BindingToNormalizedNodeCodec instance.
19  *
20  * @author Thomas Pantelis
21  */
22 public class BindingToNormalizedNodeCodecFactory {
23     private static final AtomicBoolean INSTANCE_CREATED = new AtomicBoolean();
24     private static volatile BindingToNormalizedNodeCodec instance;
25
26     /**
27      * Returns the global BindingToNormalizedNodeCodec instance, creating if necessary. The returned instance
28      * is registered with tthe SchemaService as a SchemaContextListener.
29      *
30      * @param classLoadingStrategy
31      * @param schemaService
32      * @return the BindingToNormalizedNodeCodec instance
33      */
34     public static BindingToNormalizedNodeCodec getOrCreateInstance(ClassLoadingStrategy classLoadingStrategy,
35             SchemaService schemaService) {
36         if(!INSTANCE_CREATED.compareAndSet(false, true)) {
37             return instance;
38         }
39
40         BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(
41                 StreamWriterGenerator.create(SingletonHolder.JAVASSIST));
42         BindingToNormalizedNodeCodec localInstance = new BindingToNormalizedNodeCodec(
43                 classLoadingStrategy, codecRegistry, true);
44
45         schemaService.registerSchemaContextListener(localInstance);
46
47         // Publish the BindingToNormalizedNodeCodec instance after we've registered it as a
48         // SchemaContextListener to avoid a race condition by publishing it too early when it isn't
49         // fully initialized.
50         instance = localInstance;
51         return instance;
52     }
53
54     public static BindingToNormalizedNodeCodec getInstance() {
55         return instance;
56     }
57 }