Fix checkstyle violations in yang-binding
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / util / StringValueObjectFactory.java
1 /*
2  * Copyright (c) 2016 Pantheon Technologies s.r.o. 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.yangtools.yang.binding.util;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import java.lang.invoke.MethodHandle;
14 import java.lang.invoke.MethodHandles;
15 import java.lang.invoke.MethodHandles.Lookup;
16 import java.lang.invoke.MethodType;
17 import java.lang.reflect.Constructor;
18 import java.lang.reflect.Field;
19 import java.lang.reflect.InvocationTargetException;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 /**
24  * Utility class for instantiating value-type generated objects with String being the base type. Unlike the normal
25  * constructor, instances of this class bypass string validation.
26  *
27  * <p>
28  * THE USE OF THIS CLASS IS DANGEROUS AND SHOULD ONLY BE USED TO IMPLEMENT WELL-AUDITED AND CORRECT UTILITY METHODS
29  * SHIPPED WITH MODELS TO PROVIDE INSTANTIATION FROM TYPES DIFFERENT THAN STRING.
30  *
31  * <p>
32  * APPLICATION CODE <em>MUST NOT</em> USE THIS CLASS DIRECTLY. VIOLATING THIS CONSTRAINT HAS SECURITY AND CORRECTNESS
33  * IMPLICATIONS ON EVERY USER INTERACTING WITH THE RESULTING OBJECTS.
34  *
35  * @param <T> Resulting object type
36  */
37 @Beta
38 public final class StringValueObjectFactory<T> {
39     private static final MethodType CONSTRUCTOR_METHOD_TYPE = MethodType.methodType(Object.class, Object.class);
40     private static final MethodType SETTER_METHOD_TYPE = MethodType.methodType(void.class, Object.class, String.class);
41     private static final Logger LOG = LoggerFactory.getLogger(StringValueObjectFactory.class);
42     private static final Lookup LOOKUP = MethodHandles.lookup();
43
44     private final MethodHandle constructor;
45     private final MethodHandle setter;
46     private final T template;
47
48     private StringValueObjectFactory(final T template, final MethodHandle constructor, final MethodHandle setter) {
49         this.template = Preconditions.checkNotNull(template);
50         this.constructor = constructor.bindTo(template);
51         this.setter = Preconditions.checkNotNull(setter);
52     }
53
54     public static <T> StringValueObjectFactory<T> create(final Class<T> clazz, final String templateString) {
55         final Constructor<T> stringConstructor;
56         try {
57             stringConstructor = clazz.getConstructor(String.class);
58         } catch (NoSuchMethodException e) {
59             throw new IllegalArgumentException(String.format("%s does not have a String constructor", clazz), e);
60         }
61
62         final T template;
63         try {
64             template = stringConstructor.newInstance(templateString);
65         } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
66             throw new IllegalArgumentException(String.format("Failed to instantiate template %s for '%s'", clazz,
67                 templateString), e);
68         }
69
70         final Constructor<T> copyConstructor;
71         try {
72             copyConstructor = clazz.getConstructor(clazz);
73         } catch (NoSuchMethodException e) {
74             throw new IllegalArgumentException(String.format("%s does not have a copy constructor", clazz), e);
75         }
76
77         final Field f;
78         try {
79             f = clazz.getDeclaredField("_value");
80         } catch (NoSuchFieldException e) {
81             throw new IllegalArgumentException(String.format("%s does not have required internal field", clazz), e);
82         }
83         f.setAccessible(true);
84
85         final StringValueObjectFactory<T> ret;
86         try {
87             ret = new StringValueObjectFactory<>(template,
88                     LOOKUP.unreflectConstructor(copyConstructor).asType(CONSTRUCTOR_METHOD_TYPE),
89                     LOOKUP.unreflectSetter(f).asType(SETTER_METHOD_TYPE));
90         } catch (IllegalAccessException e) {
91             throw new IllegalStateException("Failed to instantiate method handles", e);
92         }
93
94         // Let us be very defensive and scream loudly if the invocation does not come from the same package. This
95         // is far from perfect, but better than nothing.
96         final Throwable t = new Throwable("Invocation stack");
97         t.fillInStackTrace();
98         if (matchesPackage(clazz.getPackage().getName(), t.getStackTrace())) {
99             LOG.info("Instantiated factory for {}", clazz);
100         } else {
101             LOG.warn("Instantiated factory for {} outside its package", clazz, t);
102         }
103
104         return ret;
105     }
106
107     private static boolean matchesPackage(final String pkg, final StackTraceElement[] stackTrace) {
108         for (StackTraceElement e : stackTrace) {
109             final String sp = e.getClassName();
110             if (sp.startsWith(pkg) && sp.lastIndexOf('.') == pkg.length()) {
111                 return true;
112             }
113         }
114
115         return false;
116     }
117
118     @SuppressWarnings("checkstyle:illegalCatch")
119     public T newInstance(final String string) {
120         Preconditions.checkNotNull(string, "Argument may not be null");
121
122         try {
123             final T ret = (T) constructor.invokeExact();
124             setter.invokeExact(ret, string);
125             LOG.trace("Instantiated new object {} value {}", ret.getClass(), string);
126             return ret;
127         } catch (Throwable e) {
128             Throwables.throwIfUnchecked(e);
129             throw new RuntimeException(e);
130         }
131     }
132
133     public T getTemplate() {
134         return template;
135     }
136 }