Example usage for java.net URI getAuthority

List of usage examples for java.net URI getAuthority

Introduction

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

Prototype

public String getAuthority() 

Source Link

Document

Returns the decoded authority component of this URI.

Usage

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/*from  w  w  w  . j av a 2s. 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());
}

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

/**
 * <p>/* ww  w.ja va2s .c o m*/
 * Ensures that all the components of the {@link URI} are in lower-case.
 * </p>
 *
 * <p>
 * If the specified {@link URI} is opaque, it is returned. Otherwise, a new
 * {@link URI} is returned that is identical to the specified {@link URI}
 * except that the components (scheme, hostname, path) are converted to
 * their lower case equivalents (in a generic locale.)
 * </p>
 *
 * @param uri
 *        a {@link URI} to check (must not be <code>null</code>)
 * @return a {@link URI} as described above (never <code>null</code>)
 */
public static URI toLowerCase(final URI uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    if (uri.isOpaque()) {
        return uri;
    }

    final String scheme = uri.getScheme() != null ? uri.getScheme().toLowerCase(LocaleUtil.ROOT) : null;
    final String authority = uri.getAuthority() != null ? uri.getAuthority().toLowerCase(LocaleUtil.ROOT)
            : null;
    final String path = uri.getPath() != null ? uri.getPath().toLowerCase(LocaleUtil.ROOT) : null;
    final String query = uri.getQuery() != null ? uri.getQuery().toLowerCase(LocaleUtil.ROOT) : null;
    final String fragment = uri.getFragment() != null ? uri.getFragment().toLowerCase(LocaleUtil.ROOT) : null;

    return newURI(scheme, authority, path, query, fragment);
}

From source file:org.apache.hive.jdbc.Utils.java

/**
 * Get a string representing a specific host:port
 * @param connParams/*w w w. j a  v a2s  .com*/
 * @return
 * @throws JdbcUriParseException
 * @throws ZooKeeperHiveClientException
 */
private static String resolveAuthority(JdbcConnectionParams connParams)
        throws JdbcUriParseException, ZooKeeperHiveClientException {
    String serviceDiscoveryMode = connParams.getSessionVars().get(JdbcConnectionParams.SERVICE_DISCOVERY_MODE);
    if ((serviceDiscoveryMode != null)
            && (JdbcConnectionParams.SERVICE_DISCOVERY_MODE_ZOOKEEPER.equalsIgnoreCase(serviceDiscoveryMode))) {
        // Resolve using ZooKeeper
        return resolveAuthorityUsingZooKeeper(connParams);
    } else {
        String authority = connParams.getAuthorityList()[0];
        URI jdbcURI = URI.create(URI_HIVE_PREFIX + "//" + authority);
        // Check to prevent unintentional use of embedded mode. A missing "/"
        // to separate the 'path' portion of URI can result in this.
        // The missing "/" common typo while using secure mode, eg of such url -
        // jdbc:hive2://localhost:10000;principal=hive/HiveServer2Host@YOUR-REALM.COM
        if ((jdbcURI.getAuthority() != null) && (jdbcURI.getHost() == null)) {
            throw new JdbcUriParseException(
                    "Bad URL format. Hostname not found " + " in authority part of the url: "
                            + jdbcURI.getAuthority() + ". Are you missing a '/' after the hostname ?");
        }
        // Return the 1st element of the array
        return jdbcURI.getAuthority();
    }
}

From source file:Main.java

/**
 * Removes dot segments according to RFC 3986, section 5.2.4
 *
 * @param uri the original URI//from w  w w . j a v  a 2 s  .c om
 * @return the URI without dot segments
 */
private static URI removeDotSegments(URI uri) {
    String path = uri.getPath();
    if ((path == null) || (path.indexOf("/.") == -1)) {
        // No dot segments to remove
        return uri;
    }
    String[] inputSegments = path.split("/");
    Stack<String> outputSegments = new Stack<String>();
    for (int i = 0; i < inputSegments.length; i++) {
        if ((inputSegments[i].length() == 0) || (".".equals(inputSegments[i]))) {
            // Do nothing
        } else if ("..".equals(inputSegments[i])) {
            if (!outputSegments.isEmpty()) {
                outputSegments.pop();
            }
        } else {
            outputSegments.push(inputSegments[i]);
        }
    }
    StringBuilder outputBuffer = new StringBuilder();
    for (String outputSegment : outputSegments) {
        outputBuffer.append('/').append(outputSegment);
    }
    try {
        return new URI(uri.getScheme(), uri.getAuthority(), outputBuffer.toString(), uri.getQuery(),
                uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.apache.bookkeeper.common.net.ServiceURI.java

/**
 * Create a service uri instance from a {@link URI} instance.
 *
 * @param uri {@link URI} instance//w  w w  .  j av a 2 s .  c om
 * @return a service uri instance
 * @throws NullPointerException if {@code uriStr} is null
 * @throws IllegalArgumentException if the given string violates RFC&nbsp;2396
 */
public static ServiceURI create(URI uri) {
    checkNotNull(uri, "service uri instance is null");

    String serviceName;
    String[] serviceInfos = new String[0];
    String scheme = uri.getScheme();
    if (null != scheme) {
        scheme = scheme.toLowerCase();
        final String serviceSep;
        if (scheme.startsWith(SERVICE_DLOG)) {
            serviceSep = SERVICE_DLOG_SEP;
        } else {
            serviceSep = SERVICE_SEP;
        }
        String[] schemeParts = StringUtils.split(scheme, serviceSep);
        serviceName = schemeParts[0];
        serviceInfos = new String[schemeParts.length - 1];
        System.arraycopy(schemeParts, 1, serviceInfos, 0, serviceInfos.length);
    } else {
        serviceName = null;
    }

    String userAndHostInformation = uri.getAuthority();
    checkArgument(!Strings.isNullOrEmpty(userAndHostInformation),
            "authority component is missing in service uri : " + uri);

    String serviceUser;
    List<String> serviceHosts;
    int atIndex = userAndHostInformation.indexOf('@');
    Splitter splitter = Splitter.on(CharMatcher.anyOf(",;"));
    if (atIndex > 0) {
        serviceUser = userAndHostInformation.substring(0, atIndex);
        serviceHosts = splitter.splitToList(userAndHostInformation.substring(atIndex + 1));
    } else {
        serviceUser = null;
        serviceHosts = splitter.splitToList(userAndHostInformation);
    }
    serviceHosts = serviceHosts.stream().map(host -> validateHostName(serviceName, host))
            .collect(Collectors.toList());

    String servicePath = uri.getPath();
    checkArgument(null != servicePath, "service path component is missing in service uri : " + uri);

    return new ServiceURI(serviceName, serviceInfos, serviceUser,
            serviceHosts.toArray(new String[serviceHosts.size()]), servicePath, uri);
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

private static String getMethodHost(HttpRequestBase method) {
    URI uri = method.getURI();
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    return scheme + "://" + uri.getAuthority();
}

From source file:org.apache.hadoop.filecache.TrackerDistributedCacheManager.java

private static Path coreLocation(String uriString, Configuration conf) throws InvalidJobConfException {
    // lose the fragment, if it's likely to be a symlink name
    if (DistributedCache.getSymlink(conf)) {
        try {// w  w  w  . ja  v  a2s .  c  o  m
            URI uri = new URI(uriString);
            uriString = (new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, null).toString());
        } catch (URISyntaxException e) {
            throw new InvalidJobConfException("Badly formatted URI: " + uriString, e);
        }
    }

    Path path = new Path(uriString);

    try {
        path = path.makeQualified(path.getFileSystem(conf));
    } catch (IOException e) {
        throw new InvalidJobConfException("Invalid file system in distributed cache for the URI: " + uriString,
                e);
    }

    return path;
}

From source file:org.apache.hadoop.hive.ql.parse.ImportSemanticAnalyzer.java

public static boolean prepareImport(boolean isLocationSet, boolean isExternalSet, boolean isPartSpecSet,
        boolean waitOnPrecursor, String parsedLocation, String parsedTableName, String parsedDbName,
        LinkedHashMap<String, String> parsedPartSpec, String fromLocn,
        EximUtil.SemanticAnalyzerWrapperContext x, Map<String, Long> dbsUpdated,
        Map<String, Long> tablesUpdated) throws IOException, MetaException, HiveException, URISyntaxException {

    // initialize load path
    URI fromURI = EximUtil.getValidatedURI(x.getConf(), stripQuotes(fromLocn));
    Path fromPath = new Path(fromURI.getScheme(), fromURI.getAuthority(), fromURI.getPath());

    FileSystem fs = FileSystem.get(fromURI, x.getConf());
    x.getInputs().add(toReadEntity(fromPath, x.getConf()));

    MetaData rv = new MetaData();
    try {/*from   w  w w.ja v  a 2  s  . c  o m*/
        rv = EximUtil.readMetaData(fs, new Path(fromPath, EximUtil.METADATA_NAME));
    } catch (IOException e) {
        throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(), e);
    }

    ReplicationSpec replicationSpec = rv.getReplicationSpec();
    if (replicationSpec.isNoop()) {
        // nothing to do here, silently return.
        return false;
    }

    String dbname = SessionState.get().getCurrentDatabase();
    if ((parsedDbName != null) && (!parsedDbName.isEmpty())) {
        // If the parsed statement contained a db.tablename specification, prefer that.
        dbname = parsedDbName;
    }
    if (dbsUpdated != null) {
        dbsUpdated.put(dbname, Long.valueOf(replicationSpec.get(ReplicationSpec.KEY.EVENT_ID)));
    }

    // Create table associated with the import
    // Executed if relevant, and used to contain all the other details about the table if not.
    ImportTableDesc tblDesc;
    try {
        tblDesc = getBaseCreateTableDescFromTable(dbname, rv.getTable());
    } catch (Exception e) {
        throw new HiveException(e);
    }

    if ((replicationSpec != null) && replicationSpec.isInReplicationScope()) {
        tblDesc.setReplicationSpec(replicationSpec);
    }

    if (isExternalSet) {
        tblDesc.setExternal(isExternalSet);
        // This condition-check could have been avoided, but to honour the old
        // default of not calling if it wasn't set, we retain that behaviour.
        // TODO:cleanup after verification that the outer if isn't really needed here
    }

    if (isLocationSet) {
        tblDesc.setLocation(parsedLocation);
        x.getInputs().add(toReadEntity(new Path(parsedLocation), x.getConf()));
    }

    if ((parsedTableName != null) && (!parsedTableName.isEmpty())) {
        tblDesc.setTableName(parsedTableName);
    }
    if (tablesUpdated != null) {
        tablesUpdated.put(dbname + "." + tblDesc.getTableName(),
                Long.valueOf(replicationSpec.get(ReplicationSpec.KEY.EVENT_ID)));
    }

    List<AddPartitionDesc> partitionDescs = new ArrayList<AddPartitionDesc>();
    Iterable<Partition> partitions = rv.getPartitions();
    for (Partition partition : partitions) {
        // TODO: this should ideally not create AddPartitionDesc per partition
        AddPartitionDesc partsDesc = getBaseAddPartitionDescFromPartition(fromPath, dbname, tblDesc, partition);
        partitionDescs.add(partsDesc);
    }

    if (isPartSpecSet) {
        // The import specification asked for only a particular partition to be loaded
        // We load only that, and ignore all the others.
        boolean found = false;
        for (Iterator<AddPartitionDesc> partnIter = partitionDescs.listIterator(); partnIter.hasNext();) {
            AddPartitionDesc addPartitionDesc = partnIter.next();
            if (!found && addPartitionDesc.getPartition(0).getPartSpec().equals(parsedPartSpec)) {
                found = true;
            } else {
                partnIter.remove();
            }
        }
        if (!found) {
            throw new SemanticException(
                    ErrorMsg.INVALID_PARTITION.getMsg(" - Specified partition not found in import directory"));
        }
    }

    if (tblDesc.getTableName() == null) {
        // Either we got the tablename from the IMPORT statement (first priority)
        // or from the export dump.
        throw new SemanticException(ErrorMsg.NEED_TABLE_SPECIFICATION.getMsg());
    } else {
        x.getConf().set("import.destination.table", tblDesc.getTableName());
        for (AddPartitionDesc addPartitionDesc : partitionDescs) {
            addPartitionDesc.setTableName(tblDesc.getTableName());
        }
    }

    Warehouse wh = new Warehouse(x.getConf());
    Table table = tableIfExists(tblDesc, x.getHive());
    boolean tableExists = false;

    if (table != null) {
        checkTable(table, tblDesc, replicationSpec, x.getConf());
        x.getLOG().debug("table " + tblDesc.getTableName() + " exists: metadata checked");
        tableExists = true;
    }

    if (!replicationSpec.isInReplicationScope()) {
        createRegularImportTasks(tblDesc, partitionDescs, isPartSpecSet, replicationSpec, table, fromURI, fs,
                wh, x);
    } else {
        createReplImportTasks(tblDesc, partitionDescs, isPartSpecSet, replicationSpec, waitOnPrecursor, table,
                fromURI, fs, wh, x);
    }
    return tableExists;
}

From source file:org.apache.hadoop.hive.common.FileUtils.java

/**
 * Variant of Path.makeQualified that qualifies the input path against the default file system
 * indicated by the configuration//  w w w .j  av  a 2  s.  c  om
 *
 * This does not require a FileSystem handle in most cases - only requires the Filesystem URI.
 * This saves the cost of opening the Filesystem - which can involve RPCs - as well as cause
 * errors
 *
 * @param path
 *          path to be fully qualified
 * @param conf
 *          Configuration file
 * @return path qualified relative to default file system
 */
public static Path makeQualified(Path path, Configuration conf) throws IOException {

    if (!path.isAbsolute()) {
        // in this case we need to get the working directory
        // and this requires a FileSystem handle. So revert to
        // original method.
        return path.makeQualified(FileSystem.get(conf));
    }

    URI fsUri = FileSystem.getDefaultUri(conf);
    URI pathUri = path.toUri();

    String scheme = pathUri.getScheme();
    String authority = pathUri.getAuthority();

    // validate/fill-in scheme and authority. this follows logic
    // identical to FileSystem.get(URI, conf) - but doesn't actually
    // obtain a file system handle

    if (scheme == null) {
        // no scheme - use default file system uri
        scheme = fsUri.getScheme();
        authority = fsUri.getAuthority();
        if (authority == null) {
            authority = "";
        }
    } else {
        if (authority == null) {
            // no authority - use default one if it applies
            if (scheme.equals(fsUri.getScheme()) && fsUri.getAuthority() != null) {
                authority = fsUri.getAuthority();
            } else {
                authority = "";
            }
        }
    }

    return new Path(scheme, authority, pathUri.getPath());
}

From source file:com.buaa.cfs.fs.AbstractFileSystem.java

private static URI getBaseUri(URI uri) {
    String scheme = uri.getScheme();
    String authority = uri.getAuthority();
    String baseUriString = scheme + "://";
    if (authority != null) {
        baseUriString = baseUriString + authority;
    } else {/*from ww  w .  j a  v  a  2  s  .com*/
        baseUriString = baseUriString + "/";
    }
    return URI.create(baseUriString);
}