Merge "Global cleanup of restconf client dependencies"
[yangtools.git] / common / concepts / src / main / java / org / opendaylight / yangtools / concepts / util / Immutables.java
1 /*
2  * Copyright (c) 2014 Cisco 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.yangtools.concepts.util;
9
10 import java.math.BigDecimal;
11 import java.math.BigInteger;
12 import java.util.Collections;
13 import java.util.HashSet;
14 import java.util.Set;
15 import java.util.concurrent.atomic.AtomicInteger;
16 import java.util.concurrent.atomic.AtomicLong;
17
18 import org.opendaylight.yangtools.concepts.Immutable;
19 import org.opendaylight.yangtools.concepts.Mutable;
20
21 public class Immutables {
22
23     private Immutables() {
24         throw new UnsupportedOperationException("Helper class");
25     }
26
27     public static final Set<Class<?>> KNOWN_IMMUTABLES = Immutables.<Class<?>> asHashSet(
28             //
29             Integer.class, Short.class, BigDecimal.class, BigInteger.class, Byte.class, Character.class, Double.class,
30             Float.class);
31
32     /**
33      * Determines if object is known to be immutable
34      * 
35      * Note: This method may return false to immutable objects which
36      * immutability is not known, was defined not using concepts term.
37      * 
38      * @param o
39      *            Reference to check
40      * @return true if object is known to be immutable false otherwise.
41      */
42     public static boolean isImmutable(Object o) {
43         if (o == null) {
44             throw new IllegalArgumentException("Object should not be null");
45         }
46         if (o instanceof Mutable) {
47             return false;
48         } else if (o instanceof Immutable) {
49             return true;
50         } else if (o instanceof String) {
51             return true;
52         } else if (KNOWN_IMMUTABLES.contains(o.getClass())) {
53             return true;
54         }
55         return false;
56     }
57
58     private static boolean isNumberImmutable(Number o) {
59         if(o instanceof AtomicInteger) {
60             return false;
61         } else if(o instanceof AtomicLong) {
62             return false;
63         } else if(o instanceof Short) {
64             return true;
65         }
66         return false;
67     }
68
69     @SafeVarargs
70     private static <E> Set<E> asHashSet(E... list) {
71         HashSet<E> ret = new HashSet<>();
72         for (E e : list) {
73             ret.add(e);
74         }
75         return Collections.unmodifiableSet(ret);
76     }
77 }