aboutsummaryrefslogtreecommitdiffstats
path: root/jdisc_core/src/main/java/com/yahoo/jdisc/core/BundleLocationResolver.java
blob: 126a93fe67599f9fb39fff202284c14adbf40c3c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;

import java.io.File;
import java.io.IOException;

/**
 * @author Simon Thoresen Hult
 */
class BundleLocationResolver {

    static final String BUNDLE_PATH = System.getProperty("jdisc.bundle.path", ".") + "/";

    public static String resolve(String bundleLocation) {
        bundleLocation = expandSystemProperties(bundleLocation);
        bundleLocation = bundleLocation.trim();
        String scheme = getLocationScheme(bundleLocation);
        if (scheme == null) {
            bundleLocation = "file:" + getCanonicalPath(BUNDLE_PATH + bundleLocation);
        } else if (scheme.equalsIgnoreCase("file")) {
            bundleLocation = "file:" + getCanonicalPath(bundleLocation.substring(5));
        }
        return bundleLocation;
    }

    private static String expandSystemProperties(String str) {
        StringBuilder ret = new StringBuilder();
        int prev = 0;
        while (true) {
            int from = str.indexOf("${", prev);
            if (from < 0) {
                break;
            }
            ret.append(str.substring(prev, from));
            prev = from;

            int to = str.indexOf("}", from);
            if (to < 0) {
                break;
            }
            ret.append(System.getProperty(str.substring(from + 2, to), ""));
            prev = to + 1;
        }
        if (prev >= 0) {
            ret.append(str.substring(prev));
        }
        return ret.toString();
    }

    private static String getCanonicalPath(String path) {
        try {
            return new File(path).getCanonicalPath();
        } catch (IOException e) {
            return path;
        }
    }

    private static String getLocationScheme(String bundleLocation) {
        char[] arr = bundleLocation.toCharArray();
        for (int i = 0; i < arr.length; ++i) {
            if (arr[i] == ':' && i > 0) {
                return bundleLocation.substring(0, i);
            }
            if (!Character.isLetterOrDigit(arr[i])) {
                return null;
            }
        }
        return null;
    }
}