Example usage for java.net URI resolve

List of usage examples for java.net URI resolve

Introduction

In this page you can find the example usage for java.net URI resolve.

Prototype

public URI resolve(String str) 

Source Link

Document

Constructs a new URI by parsing the given string and then resolving it against this URI.

Usage

From source file:com.sworddance.util.UriFactoryImpl.java

/**
 * Converts the given href value to an absolute uri.
 * The html document's baseHtmlElement and
 * baseUri are used in order to derive the
 * correct location of the resource.//from w  w w .jav a  2  s .co m
 *
 * @param href accepts null
 * @param baseUri
 * @param baseHtmlElement
 * @return the URI
 *
 * @throws IllegalArgumentException if the uri resolution encounters
 * {@link URI#create(String) problems}.
 */
public static URI absolutize(String href, URI baseUri, String baseHtmlElement) {
    if (href == null) {
        href = "";
    }
    URI uri = createUri(href);
    if (uri != null && uri.isAbsolute()) {
        return uri;
    }

    String start = absolutize(baseUri, baseHtmlElement);
    if (!start.endsWith(PATH_SEPARATOR)) {
        start += PATH_SEPARATOR;
    }
    URI startUri = createUri(start);
    if (uri != null) {
        return startUri.resolve(uri);
    } else {
        return startUri;
    }
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UMLSHistoryFileToSQL.java

public static void validateFile(URI fileLocation, String token, boolean validateLevel) throws Exception {

    BufferedReader reader = null;
    int lineNo = 1;
    if (token == null) {
        token = token_;//from ww w  .  j  a  v  a2s.  com
    }

    // test MRCUI.RRF
    URI mrCUIFile = fileLocation.resolve("MRCUI.RRF");
    if (mrCUIFile == null) {

        throw new ConnectionFailure("Did not find the expected MRCUI.RRF file in the location provided.");
    }
    if (mrCUIFile.getScheme().equals("file")) {

        new FileReader(new File(mrCUIFile)).close();
    } else {
        new InputStreamReader(mrCUIFile.toURL().openConnection().getInputStream()).close();
    }

    try {
        reader = getReader(mrCUIFile);
        String line = reader.readLine();
        lineNo = 1;
        boolean notAMonth = false;
        while (line != null) {

            if (line.startsWith("#") || line.length() == 0) {
                line = reader.readLine();
                continue;
            }

            if (validateLevel && lineNo > 10) {
                break;
            }

            List<String> elements = deTokenizeString(line, token_);

            if (elements.size() != 7) {
                throw new Exception(
                        "MRCUI.RRF " + "(" + "Line:" + lineNo + ")" + " is not in the required format.");
            }
            if (!elements.get(0).toLowerCase().startsWith("c")) {
                throw new Exception("MRCUI.RRF " + "(" + "Line:" + lineNo + "): " + "The concept("
                        + elements.get(0) + ") is not in the required format.");
            }

            try {
                String month = elements.get(1).substring(4);
                int i = Integer.parseInt(month);
                if (i < 0 || i > 12) {
                    throw new Exception();
                } else {
                    notAMonth = false;
                }
            } catch (Exception e) {
                notAMonth = true;
            }

            if (!elements.get(1).endsWith("AA") && !elements.get(1).endsWith("AB")
                    && !elements.get(1).endsWith("AC") && !elements.get(1).endsWith("AD") && notAMonth) {
                throw new Exception("MRCUI.RRF " + "(" + "Line:" + lineNo + "): " + "The Release id ("
                        + elements.get(1) + ") is not in the required format.");
            }
            lineNo++;
            line = reader.readLine();
        }

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        reader.close();
    }

    // test MRCONSO.RRF
    URI mrCONSOFile = fileLocation.resolve("MRCONSO.RRF");
    if (mrCONSOFile == null) {

        throw new ConnectionFailure("Did not find the expected MRCONSO.RRF file in the location provided.");
    }
    if (mrCONSOFile.getScheme().equals("file")) {

        new FileReader(new File(mrCONSOFile)).close();
    } else {
        new InputStreamReader(mrCONSOFile.toURL().openConnection().getInputStream()).close();
    }

    try {
        reader = getReader(mrCONSOFile);
        String line = reader.readLine();
        lineNo = 1;
        while (line != null) {

            if (line.startsWith("#") || line.length() == 0) {
                line = reader.readLine();
                continue;
            }

            if (validateLevel && lineNo > 10) {
                break;
            }

            List<String> elements = deTokenizeString(line, token_);

            if (elements.size() != 18) {
                throw new Exception(
                        "MRCONSO.RRF " + "(" + "Line:" + lineNo + ")" + " is not in the required format.");
            }

            lineNo++;
            line = reader.readLine();
        }

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        reader.close();
    }
}

From source file:com.vaadin.sass.testcases.scss.W3ConformanceTests.java

public static void extractCSS(final URI url, File targetdir) throws Exception {
    /*/*from w  w  w .  j  a va  2 s  .  c  o m*/
     * For each test URL: 1) extract <style> tag contents 2) extract from
     * <link rel="stylesheet"> files 3) extract inline style attributes from
     * all elements and wrap the result in .style {}
     */

    Document doc = Jsoup.connect(url.toString()).timeout(20000).get();

    List<String> tests = new ArrayList<String>();

    for (Element e : doc.select("style[type=text/css]")) {
        tests.add(e.data());
    }

    for (Element e : doc.select("link[rel=stylesheet][href][type=text/css]")) {
        URI cssUri = new URI(e.attr("href"));
        if (!cssUri.isAbsolute()) {
            cssUri = url.resolve(cssUri);
        }
        String encoding = doc.outputSettings().charset().name();
        tests.add(IOUtils.toString(cssUri, encoding));
    }

    for (Element e : doc.select("*[style]")) {
        tests.add(String.format(".style { %s }", e.attr("style")));
    }

    for (final String test : tests) {
        targetdir.mkdirs();
        String logfile = String.format("%s.%d.scss", FilenameUtils.getBaseName(url.toString()),
                tests.indexOf(test));
        PrintStream dataLogger = new PrintStream(new File(targetdir, logfile));

        dataLogger.println("/* Source: " + url + " */");
        dataLogger.println(test);

    }
}

From source file:org.rssowl.core.util.URIUtils.java

/**
 * @param base the base {@link URI} to resolve against.
 * @param relative the relative {@link URI} to resolve.
 * @return a resolved {@link URI} that is absolute.
 * @throws URISyntaxException in case of an error while resolving.
 *//*from ww  w. jav  a  2  s.c  o m*/
public static URI resolve(URI base, URI relative) throws URISyntaxException {
    if (relative.isAbsolute())
        return relative;

    /* Resolve against Host */
    if (relative.toString().startsWith("/")) { //$NON-NLS-1$
        base = normalizeUri(base, true);
        return base.resolve(relative);
    }

    /* Resolve against Given Base */
    if (base.toString().endsWith("/")) //$NON-NLS-1$
        return base.resolve(relative);

    /* Resolve against Given Base By Appending Leading Slash */
    return new URI(base.toString() + "/").resolve(relative.toString()); //$NON-NLS-1$
}

From source file:com.sworddance.util.UriFactoryImpl.java

public static URI createUriWithSchema(Object uriStr, Object path) {

    URI baseUri = createUriWithOptions(uriStr, true, false);
    if (path == null) {
        return baseUri;
    } else {/*from ww w .j  a  va  2  s . co m*/
        return baseUri.resolve(path.toString());
    }
}

From source file:org.esigate.util.UriUtils.java

/**
 * Interpret the url relatively to the request url (may be relative). Due to a bug in {@link URI} class when using a
 * relUri containing only a query string, we cannot use directly the method provided by {@link URI} class.
 * /*from   w  w  w . j  av a 2s.c o m*/
 * @param relUri
 *            the relative URI
 * @param base
 *            the reference {@link URI}
 * @return the resolved {@link URI}
 */
public static URI resolve(String relUri, URI base) {
    URI uri = createURI(relUri);
    if (uri.getScheme() == null && uri.getUserInfo() == null && uri.getHost() == null && uri.getPort() == -1
            && StringUtils.isEmpty(uri.getPath()) && uri.getQuery() != null) {
        try {
            return new URI(base.getScheme(), base.getUserInfo(), base.getHost(), base.getPort(), base.getPath(),
                    uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            throw new InvalidUriException(e);
        }
    } else {
        return base.resolve(uri);
    }
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UmlsCommon.LoadRRFToDB.java

private static String[] createAndLoadTables(URI rrfLocation, boolean skipNonLexGridFiles,
        boolean recalcRootOnly, String dbServer, String dbDriver, String username, String password,
        LgMessageDirectorIF md, boolean validateMode) throws Exception {
    md.info("Connecting to RRF Files");
    BufferedReader reader = getReader(rrfLocation.resolve("MRFILES.RRF"));

    md.info("Connecting to db Files");
    Connection sqlConnection = DBUtility.connectToDatabase(dbServer, dbDriver, username, password);

    GenericSQLModifier gsm = new GenericSQLModifier(sqlConnection);

    Hashtable columnTypeMap = readMRCols(rrfLocation);
    Hashtable tableColumnMap = new Hashtable();

    List tables = new ArrayList();

    if (skipNonLexGridFiles) {
        // the only tables that I need to load
        tables.add("MRCONSO");
        tables.add("MRDOC");
        tables.add("MRREL");
        tables.add("MRSAB");
        tables.add("MRRANK");

        if (!recalcRootOnly) {
            tables.add("MRDEF");
            tables.add("MRSTY");
            tables.add("MRSAT");
            tables.add("MRHIER");
        }//from  w w w.  java  2 s .  co m
    }

    md.info("Creating SQL database tables");

    PreparedStatement create = null;
    PreparedStatement drop = null;
    String line = reader.readLine();

    int mrhierHCDCol = -1;
    while (line != null) {
        String[] vals = stringToArray(line, '|');

        // for MRFILES, all I care about is the following
        String file = vals[0];
        String tableName = file.substring(0, file.indexOf('.'));

        // if file is MRHIER, remember HCD column number (base 0)
        if ("MRHIER".equalsIgnoreCase(tableName) && vals.length > 1) {
            mrhierHCDCol = Arrays.asList(vals[2].split(",")).indexOf("HCD");
        }

        if (skipNonLexGridFiles || recalcRootOnly) {
            if (!tables.contains(tableName)) {
                line = reader.readLine();
                continue;
            }
        } else {
            if (file.indexOf('/') != -1) {
                // skip files in subfolders.
                line = reader.readLine();
                continue;
            }
            if (!tables.contains(tableName))
                tables.add(tableName);
        }

        String[] columns = stringToArray(vals[2], ',');

        tableColumnMap.put(file, columns);

        StringBuffer tableCreateSQL = new StringBuffer();
        tableCreateSQL.append("CREATE TABLE {IF NOT EXISTS} ^" + tableName + "^ (");

        for (int i = 0; i < columns.length; i++) {

            tableCreateSQL.append(" ^" + columns[i] + "^ "
                    + mapUMLSType((String) columnTypeMap.get(columns[i] + "|" + file)) + " default NULL,");
        }

        // chop the last comma
        tableCreateSQL.deleteCharAt(tableCreateSQL.length() - 1);
        tableCreateSQL.append(") {TYPE}");

        // make sure the table doesn't exist
        try {
            drop = sqlConnection.prepareStatement(gsm.modifySQL("DROP TABLE " + tableName + " {CASCADE}"));
            drop.executeUpdate();
            drop.close();
        } catch (SQLException e) {
            // most likely means that the table didn't exist.
        }

        create = sqlConnection.prepareStatement(gsm.modifySQL(tableCreateSQL.toString()));
        create.executeUpdate();

        create.close();

        line = reader.readLine();
    }
    reader.close();

    md.info("Creating indexes");

    PreparedStatement createIndex = null;

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi1^ ON ^MRCONSO^ (^CUI^, ^SAB^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi2^ ON ^MRCONSO^ (^CUI^, ^AUI^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi3^ ON ^MRCONSO^ (^AUI^, ^CODE^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi4^ ON ^MRREL^ (^RELA^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi5^ ON ^MRREL^ (^REL^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi6^ ON ^MRREL^ (^RUI^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi7^ ON ^MRREL^ (^SAB^, ^RELA^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi8^ ON ^MRSAB^ (^RSAB^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi9^ ON ^MRRANK^ (^SAB^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi10^ ON ^MRRANK^ (^TTY^)"));
    createIndex.executeUpdate();
    createIndex.close();

    if (!recalcRootOnly) {
        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi11^ ON ^MRDEF^ (^CUI^, ^SAB^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi12^ ON ^MRSAT^ (^METAUI^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi13^ ON ^MRSAT^ (^CUI^, ^SAB^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi14^ ON ^MRSAT^ (^CODE^, ^SAB^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi15^ ON ^MRSTY^ (^CUI^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection.prepareStatement(
                gsm.modifySQL("CREATE INDEX ^mi16^ ON ^MRHIER^ (^CUI^, ^AUI^, ^HCD^, ^SAB^, ^CXN^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi17^ ON ^MRHIER^ (^CUI^, ^SAB^, ^CXN^)"));
        createIndex.executeUpdate();
        createIndex.close();
    }

    PreparedStatement insert = null;

    Iterator allTables = tables.iterator();
    Set rootCUIs = new HashSet();
    while (allTables.hasNext()) {
        System.gc();
        String table = (String) allTables.next();
        md.info("Loading " + table);

        boolean loadingMrHier = table.equalsIgnoreCase("MRHIER");

        StringBuffer insertSQL = new StringBuffer();

        insertSQL.append("INSERT INTO " + table + " (");

        String[] vals = (String[]) tableColumnMap.get(table + ".RRF");
        for (int i = 0; i < vals.length; i++) {
            if (gsm.getDatabaseType().equals("ACCESS") && vals[i].equals("VALUE")) {
                // reserved word in MSAccess
                insertSQL.append("\"" + vals[i] + "\", ");
            } else {
                insertSQL.append(vals[i] + ", ");
            }
        }

        // chop the last comma and space
        insertSQL.deleteCharAt(insertSQL.length() - 2);
        insertSQL.append(") VALUES (");

        for (int i = 0; i < vals.length; i++) {
            insertSQL.append("?, ");
        }

        // chop the last comma and space
        insertSQL.deleteCharAt(insertSQL.length() - 2);
        insertSQL.append(")");
        insert = sqlConnection.prepareStatement(gsm.modifySQL(insertSQL.toString()));

        URI tableURI = rrfLocation.resolve(table + ".RRF");

        if (verifyTableExists(tableURI)) {
            try {
                reader = getReader(tableURI);

                int count = 1;
                line = reader.readLine();
                boolean restrictToRootCUIs = recalcRootOnly && table.equalsIgnoreCase("MRCONSO");
                boolean restrictToRootRels = recalcRootOnly && table.equalsIgnoreCase("MRREL");
                while (line != null && line.length() > 0) {
                    // Note: If we are only using the data to recalculate
                    // root nodes,
                    // we only need CUIs defining root hierarchical terms
                    // and any related
                    // relationships.
                    if (restrictToRootCUIs && !line.contains("|SRC|RHT|")) {
                        line = reader.readLine();
                        continue;
                    }
                    String[] data = stringToArray(line, '|');

                    // If processing MRHIER, we only care about entries
                    // relevant to
                    // the specified MRHIER processing option. Many entries
                    // in this file
                    // we do not require since they can be derived from
                    // MRREL.
                    // MRHIER typically is much larger since it pre-computes
                    // the entire
                    // hierarchy, so we want to conserve time and space by
                    // loading only
                    // those entries that require special handling.
                    if (loadingMrHier && mrhierHCDCol > 0 && data.length > mrhierHCDCol
                            && StringUtils.isBlank(data[mrhierHCDCol])) {
                        line = reader.readLine();
                        continue;
                    }

                    if (restrictToRootCUIs && data.length >= 1)
                        rootCUIs.add(data[0]);
                    if (restrictToRootRels && (data.length < 5
                            || (!rootCUIs.contains(data[0]) && !rootCUIs.contains(data[4])))) {
                        line = reader.readLine();
                        continue;
                    }

                    for (int i = 0; i < vals.length; i++) {
                        insert.setString(i + 1, data[i]);
                    }
                    insert.executeUpdate();

                    count++;
                    line = reader.readLine();

                    if (validateMode && count > 100) {
                        line = null;
                    }

                    if (count % 10000 == 0) {
                        md.busy();
                    }

                    if (count % 100000 == 0) {
                        md.info("Loaded " + count + " into " + table);
                    }
                }
                reader.close();
            } catch (Exception e) {
                md.fatalAndThrowException("problem loading the table " + table, e);
            }

        } else {
            md.warn("Could not load table " + table + ". This" + "most likely means the corresponding RRF file"
                    + "was not found in the source.");
        }

        insert.close();
        System.gc();
    }

    sqlConnection.close();
    return (String[]) tables.toArray(new String[tables.size()]);
}

From source file:com.microsoft.tfs.core.util.URIUtils.java

/**
 * <p>/*from   www.j ava  2  s .  c om*/
 * Resolves the specified child {@link URI} against the specified
 * {@link URI}, returning a {@link URI} as the result.
 * </p>
 *
 * <p>
 * This method behaves differently than calling {@link URI#resolve(URI)}.
 * This method first uses the {@link #ensurePathHasTrailingSlash(URI)}
 * method to ensure that the specified parent {@link URI}'s path has a
 * trailing slash. See the documentation of
 * {@link #ensurePathHasTrailingSlash(URI)} method for a reason why this is
 * necessary.
 * </p>
 *
 * @param parent
 *        a base {@link URI} to resolve against (must not be
 *        <code>null</code>)
 * @param child
 *        a relative path to resolve (must not be <code>null</code>)
 * @return a new {@link URI} as described above (never <code>null</code>)
 */
public static URI resolve(URI parent, final URI child) {
    Check.notNull(parent, "parent"); //$NON-NLS-1$
    Check.notNull(child, "child"); //$NON-NLS-1$

    if (!child.isAbsolute() && !parent.isOpaque()) {
        parent = ensurePathHasTrailingSlash(parent);
    }

    return parent.resolve(child);
}

From source file:com.sworddance.util.UriFactoryImpl.java

/**
 * @param root//w  ww.ja  v a 2s. co m
 * @param filePath
 * @param defaultFileName
 * @return resolvedUri
 */
public static URI resolveWithDefaultFile(Object root, Object filePath, String defaultFileName) {
    URI rootUri = createUriWithSchemaAndPath(root);
    ApplicationNullPointerException.notNull(rootUri, root);

    String filePathStr = sanitizePath(filePath);
    URI uri;
    if (isNotBlank(filePathStr)) {
        uri = rootUri.resolve("./" + percentEncoding(filePathStr));
    } else {
        uri = rootUri;
    }
    if (uri.toString().endsWith(PATH_SEPARATOR) && isNotBlank(defaultFileName)) {
        uri = uri.resolve("." + PATH_SEPARATOR + percentEncoding(defaultFileName));
    }
    return uri;
}

From source file:com.vmware.thinapp.common.util.AfUtil.java

/**
 * Checks whether the given URL string begins with a protocol (http://,
 * ftp://, etc.)  If it does, the string is returned unchanged.  If it does
 * not, full URL is returned and is constructed as parentUrl "/" url.
 *
 * @param url input URL string in absolute or relative form
 * @param parentUrl base URL to use if the given URL is in relative form
 * @return an absolute URL/*  w w  w  . j  ava2s .c om*/
 */
public static URI relToAbs(String url, URI parentUrl) throws URISyntaxException {
    if (!StringUtils.hasLength(url)) {
        throw new URISyntaxException(url, "The input url was empty!");
    }
    URI parent2 = new URI(parentUrl.getScheme(), parentUrl.getUserInfo(), parentUrl.getAuthority(),
            parentUrl.getPort(), parentUrl.getPath() + "/", // Parent URL path must end with "/" for
            // this to work. resolve() removes any
            // duplicates.
            parentUrl.getQuery(), parentUrl.getFragment());

    return parent2.resolve(url.trim());
}