001/* ***** BEGIN LICENSE BLOCK *****
002 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
003 *
004 * The contents of this file are subject to the Mozilla Public License Version
005 * 1.1 (the "License"); you may not use this file except in compliance with
006 * the License. You may obtain a copy of the License at
007 * http://www.mozilla.org/MPL/
008 *
009 * Software distributed under the License is distributed on an "AS IS" basis,
010 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
011 * for the specific language governing rights and limitations under the
012 * License.
013 *
014 * The Original Code is part of dcm4che, an implementation of DICOM(TM) in
015 * Java(TM), hosted at https://github.com/gunterze/dcm4che.
016 *
017 * The Initial Developer of the Original Code is
018 * Agfa Healthcare.
019 * Portions created by the Initial Developer are Copyright (C) 2011
020 * the Initial Developer. All Rights Reserved.
021 *
022 * Contributor(s):
023 * See @authors listed below
024 *
025 * Alternatively, the contents of this file may be used under the terms of
026 * either the GNU General Public License Version 2 or later (the "GPL"), or
027 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
028 * in which case the provisions of the GPL or the LGPL are applicable instead
029 * of those above. If you wish to allow use of your version of this file only
030 * under the terms of either the GPL or the LGPL, and not to allow others to
031 * use your version of this file under the terms of the MPL, indicate your
032 * decision by deleting the provisions above and replace them with the notice
033 * and other provisions required by the GPL or the LGPL. If you do not delete
034 * the provisions above, a recipient may use your version of this file under
035 * the terms of any one of the MPL, the GPL or the LGPL.
036 *
037 * ***** END LICENSE BLOCK ***** */
038
039package org.dcm4che3.util;
040
041import java.lang.reflect.Field;
042import java.math.BigInteger;
043import java.util.Arrays;
044import java.util.Map;
045import java.util.UUID;
046import java.util.regex.Pattern;
047
048import org.dcm4che3.data.Attributes;
049import org.dcm4che3.data.UID;
050import org.dcm4che3.data.VR;
051import org.dcm4che3.data.Value;
052
053/**
054 * @author Gunter Zeilinger <gunterze@gmail.com>
055 */
056public class UIDUtils {
057
058    /**
059     * UID root for UUIDs (Universally Unique Identifiers) generated in
060     * accordance with Rec. ITU-T X.667 | ISO/IEC 9834-8.
061     *
062     * see <a href="http://www.oid-info.com/get/2.25">OID repository {joint-iso-itu-t(2) uuid(25)}</a>
063     */
064    private static final String UUID_ROOT = "2.25";
065
066    private static final Pattern PATTERN =
067            Pattern.compile("[012]((\\.0)|(\\.[1-9]\\d*))+");
068
069    private static String root = UUID_ROOT;
070
071    public static final String getRoot() {
072        return root;
073    }
074
075    public static final void setRoot(String root) {
076        checkRoot(root);
077        UIDUtils.root = root;
078    }
079
080    private static void checkRoot(String root) {
081        if (root.length() > 24)
082            throw new IllegalArgumentException("root length > 24");
083        if (!isValid(root))
084            throw new IllegalArgumentException(root);
085    }
086
087    public static boolean isValid(String uid) {
088        return uid.length() <= 64 && PATTERN.matcher(uid).matches();
089    }
090
091    public static String createUID() {
092        return randomUID(root);
093    }
094
095    public static String createNameBasedUID(byte[] name) {
096        return nameBasedUID(name, root);
097    }
098
099    public static String createNameUID(byte[] name, String root) {
100        checkRoot(root);
101        return nameBasedUID(name, root);
102    }
103
104    public static String createUID(String root) {
105        checkRoot(root);
106        return randomUID(root);
107    }
108
109    public static String createUIDIfNull(String uid) {
110        return uid == null ? randomUID(root) : uid;
111    }
112
113    public static String createUIDIfNull(String uid, String root) {
114        checkRoot(root);
115        return uid == null ? randomUID(root) : uid;
116    }
117
118    private static String randomUID(String root) {
119        return toUID(root, UUID.randomUUID());
120    }
121
122    private static String nameBasedUID(byte[] name, String root) {
123        return toUID(root, UUID.nameUUIDFromBytes(name));
124    }
125
126    private static String toUID(String root, UUID uuid) {
127        byte[] b17 = new byte[17];
128        ByteUtils.longToBytesBE(uuid.getMostSignificantBits(), b17, 1);
129        ByteUtils.longToBytesBE(uuid.getLeastSignificantBits(), b17, 9);
130        String uuidStr = new BigInteger(b17).toString();
131        int rootlen = root.length();
132        int uuidlen = uuidStr.length();
133        char[] cs = new char[rootlen + uuidlen + 1];
134        root.getChars(0, rootlen, cs, 0);
135        cs[rootlen] = '.';
136        uuidStr.getChars(0, uuidlen, cs, rootlen + 1);
137        return new String(cs);
138    }
139
140    public static StringBuilder promptTo(String uid, StringBuilder sb) {
141        return sb.append(uid).append(" - ").append(UID.nameOf(uid));
142    }
143
144    public static String[] findUIDs(String regex) {
145        Pattern p = Pattern.compile(regex);
146        Field[] fields = UID.class.getFields();
147        String[] uids = new String[fields.length];
148        int j = 0;
149        for (int i = 0; i < fields.length; i++) {
150            Field field = fields[i];
151            if (p.matcher(field.getName()).matches())
152                try {
153                    uids[j++] = (String) field.get(null);
154                } catch (Exception ignore) { }
155        }
156        return Arrays.copyOf(uids, j);
157    }
158
159    public static int remapUIDs(Attributes attrs, Map<String,String> uidMap) {
160        UIDUtils.Visitor visitor = new UIDUtils.Visitor(uidMap);
161        try {
162            attrs.accept(visitor, true);
163        } catch (Exception e) {
164            throw new RuntimeException(e);
165        }
166        return visitor.replaced;
167    }
168
169    private static class Visitor implements Attributes.Visitor {
170        private final Map<String, String> uidMap;
171        private int replaced;
172
173        public Visitor(Map<String, String> uidMap) {
174            this.uidMap = uidMap;
175        }
176
177        @Override
178        public boolean visit(Attributes attrs, int tag, VR vr, Object val) {
179            if (vr != VR.UI || val == Value.NULL)
180                return true;
181
182            String[] ss;
183            if (val instanceof byte[]) {
184                ss = attrs.getStrings(tag);
185                val = ss.length == 1 ? ss[0] : ss;
186            }
187            if (val instanceof String[]) {
188                ss = (String[]) val;
189                for (int i = 0; i < ss.length; i++) {
190                    String uid = uidMap.get(ss[i]);
191                    if (uid != null) {
192                        ss[i] = uid;
193                        replaced++;
194                    }
195                }
196            } else {
197                String uid = uidMap.get(val);
198                if (uid != null) {
199                    attrs.setString(tag, VR.UI, uid);
200                    replaced++;
201                }
202            }
203            return true;
204        }
205    }
206}