Example usage for java.net URI getHost

List of usage examples for java.net URI getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Returns the host component of this URI.

Usage

From source file:com.twitter.elephanttwin.util.HdfsUtils.java

/**
 * Returns the namenode from a fully-qualified HDFS path.
 *
 * @param hdfsPath fully-qualified HDFS path
 * @return the namenode or {@code null} if invalid HDFS path
 */// w  w  w. j a va  2s  .  c  o m
public static String getHdfsFileSystemName(@Nullable String hdfsPath) {
    if (hdfsPath == null) {
        return null;
    }
    if (!hdfsPath.startsWith("hdfs://")) {
        return null;
    }

    URI uri;
    try {
        uri = new URI(hdfsPath);
    } catch (URISyntaxException e) {
        return null;
    }

    if (uri.getPort() == -1) {
        return "hdfs://" + uri.getHost();
    }
    return "hdfs://" + uri.getHost() + ":" + uri.getPort();
}

From source file:com.ibm.jaggr.service.impl.deps.DepUtils.java

/**
 * Maps a resource URI to a {@link DepTreeNode}. This routine finds the key
 * in <code>dependencies</code> that is an ancestor of
 * <code>requiestURI</code> and then looks for the {@link DepTreeNode} who's
 * name corresponds to descendant part of the URI path.
 * //www  . jav  a 2 s.c  om
 * @param requestUri
 *            The URI for the resource location being sought
 * @param dependencies
 *            Map of file path names to root {@link DepTreeNode}s
 * @return The node corresponding to <code>requestURI</code>
 */
static public DepTreeNode getNodeForResource(URI requestUri, Map<URI, DepTreeNode> dependencies) {
    DepTreeNode result = null;
    /*
     * Iterate through the map entries and find the entry who's key is the same,
     * or an ancestor of, the specified path
     */
    for (Entry<URI, DepTreeNode> dependency : dependencies.entrySet()) {
        URI uri = dependency.getKey();
        if (requestUri.getScheme() == null && uri.getScheme() != null
                || requestUri.getScheme() != null && !requestUri.getScheme().equals(uri.getScheme()))
            continue;

        if (requestUri.getHost() == null && uri.getHost() != null
                || requestUri.getHost() != null && !requestUri.getHost().equals(uri.getHost()))
            continue;

        if (requestUri.getPath().equals(uri.getPath()) || requestUri.getPath().startsWith(uri.getPath())
                && (uri.getPath().endsWith("/") || requestUri.getPath().charAt(uri.getPath().length()) == '/')) //$NON-NLS-1$
        {
            /*
             * Found the entry.  Now find the node corresponding to the 
             * remainder of the path.
             */
            if (requestUri.getPath().equals(uri.getPath())) {
                return dependency.getValue();
            } else {
                String modulePath = requestUri.getPath().substring(uri.getPath().length());
                if (modulePath.startsWith("/")) { //$NON-NLS-1$
                    modulePath = modulePath.substring(1);
                }
                result = dependency.getValue().getDescendent(modulePath);
            }
            break;
        }
    }
    return result;
}

From source file:org.cloudfoundry.caldecott.client.TunnelHelper.java

public static Map<String, String> getTunnelServiceInfo(CloudFoundryClient client, String serviceName) {
    String urlToUse = getTunnelUri(client) + "/services/" + serviceName;
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Auth-Token", getTunnelAuth(client));
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    HttpEntity<String> response = restTemplate.exchange(urlToUse, HttpMethod.GET, requestEntity, String.class);
    String json = response.getBody().trim();
    Map<String, String> svcInfo = new HashMap<String, String>();
    try {/*from   w  w  w  .  j  a  va 2 s.c om*/
        svcInfo = convertJsonToMap(json);
    } catch (IOException e) {
        return new HashMap<String, String>();
    }
    if (svcInfo.containsKey("url")) {
        String svcUrl = svcInfo.get("url");
        try {
            URI uri = new URI(svcUrl);
            String[] userInfo;
            if (uri.getUserInfo().contains(":")) {
                userInfo = uri.getUserInfo().split(":");
            } else {
                userInfo = new String[2];
                userInfo[0] = uri.getUserInfo();
                userInfo[1] = "";
            }
            svcInfo.put("user", userInfo[0]);
            svcInfo.put("username", userInfo[0]);
            svcInfo.put("password", userInfo[1]);
            svcInfo.put("host", uri.getHost());
            svcInfo.put("hostname", uri.getHost());
            svcInfo.put("port", "" + uri.getPort());
            svcInfo.put("path", (uri.getPath().startsWith("/") ? uri.getPath().substring(1) : uri.getPath()));
            svcInfo.put("vhost", svcInfo.get("path"));
        } catch (URISyntaxException e) {
        }
    }
    return svcInfo;
}

From source file:com.ibm.jaggr.core.impl.deps.DepUtils.java

/**
 * Maps a resource URI to a {@link DepTreeNode}. This routine finds the key
 * in <code>dependencies</code> that is an ancestor of
 * <code>requiestURI</code> and then looks for the {@link DepTreeNode} who's
 * name corresponds to descendant part of the URI path.
 *
 * @param requestUri/*from w w w .  j  a v  a2 s.c  o  m*/
 *            The URI for the resource location being sought
 * @param dependencies
 *            Map of file path names to root {@link DepTreeNode}s
 * @return The node corresponding to <code>requestURI</code>
 */
static public DepTreeNode getNodeForResource(URI requestUri, Map<URI, DepTreeNode> dependencies) {
    DepTreeNode result = null;
    /*
     * Iterate through the map entries and find the entry who's key is the same,
     * or an ancestor of, the specified path
     */
    for (Entry<URI, DepTreeNode> dependency : dependencies.entrySet()) {
        URI uri = dependency.getKey();
        if (requestUri.getScheme() == null && uri.getScheme() != null
                || requestUri.getScheme() != null && !requestUri.getScheme().equals(uri.getScheme()))
            continue;

        if (requestUri.getHost() == null && uri.getHost() != null
                || requestUri.getHost() != null && !requestUri.getHost().equals(uri.getHost()))
            continue;

        if (requestUri.getPath().equals(uri.getPath()) || requestUri.getPath().startsWith(uri.getPath())
                && (uri.getPath().endsWith("/") || requestUri.getPath().charAt(uri.getPath().length()) == '/')) //$NON-NLS-1$
        {
            /*
             * Found the entry.  Now find the node corresponding to the
             * remainder of the path.
             */
            if (requestUri.getPath().equals(uri.getPath())) {
                return dependency.getValue();
            } else {
                String modulePath = requestUri.getPath().substring(uri.getPath().length());
                if (modulePath.startsWith("/")) { //$NON-NLS-1$
                    modulePath = modulePath.substring(1);
                }
                result = dependency.getValue().getDescendent(modulePath);
            }
            break;
        }
    }
    return result;
}

From source file:com.microsoft.tfs.core.credentials.internal.KeychainCredentialsManager.java

/**
 * @param uri/*from   ww  w. j  a v  a2s  . c  om*/
 *        the {@link URI} to use; should already have path and query parts
 *        removed ({@link URIUtils#removePathAndQueryParts(URI)}) (must not
 *        be <code>null</code>)
 */
private static KeychainInternetPassword newKeychainInternetPasswordFromURI(final URI uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    final KeychainInternetPassword keychainPassword = new KeychainInternetPassword();

    /*
     * Compute the protocol.
     */
    if ("http".equalsIgnoreCase(uri.getScheme())) //$NON-NLS-1$
    {
        keychainPassword.setProtocol(KeychainProtocol.HTTP);
    } else if ("https".equalsIgnoreCase(uri.getScheme())) //$NON-NLS-1$
    {
        keychainPassword.setProtocol(KeychainProtocol.HTTPS);
    } else {
        keychainPassword.setProtocol(KeychainProtocol.ANY);
    }

    if (uri.getHost() != null && uri.getHost().length() > 0) {
        keychainPassword.setServerName(uri.getHost());
    }

    if (uri.getPort() > 0) {
        keychainPassword.setPort(uri.getPort());
    }

    if (uri.getPath() != null) {
        keychainPassword.setPath(uri.getPath());
    }

    return keychainPassword;
}

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

/**
 * <p>//www  .  java 2 s .com
 * If a {@link URI} is successfully constructed but contains invalid
 * characters in the hostname (notably, underscores), the
 * {@link URI#getHost()} method returns {@link <code>null</code>}. This
 * method first gets the host using that method. If <code>null</code> is
 * returned, a best effort to get the original host (if any) is made by
 * converting the {@link URI} to a {@link URL} and calling
 * {@link URL#getHost()}.
 * </p>
 *
 * <p>
 * This method should only be used in the specific case when you want to try
 * to detect and handle the above condition. For most cases, underscores in
 * hostnames should correctly be treated as errors, and this method should
 * not be used.
 * </p>
 *
 * @param uri
 *        the {@link URI} to get the host name for (must not be
 *        <code>null</code>)
 * @return the host name of the {@link URI}, or <code>null</code> if the
 *         host name was not defined
 */
public static String safeGetHost(final URI uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    String host = uri.getHost();

    if (host == null) {
        try {
            host = uri.toURL().getHost();
        } catch (final MalformedURLException e) {
            // ignore
        }
    }

    return host;
}

From source file:jetbrains.buildServer.clouds.azure.connector.AzureApiConnector.java

private static ArrayList<ConfigurationSet> createConfigurationSetList(int port, String serverLocation) {
    ArrayList<ConfigurationSet> retval = new ArrayList<ConfigurationSet>();
    final ConfigurationSet value = new ConfigurationSet();
    value.setConfigurationSetType(ConfigurationSetTypes.NETWORKCONFIGURATION);
    final ArrayList<InputEndpoint> endpointsList = new ArrayList<InputEndpoint>();
    value.setInputEndpoints(endpointsList);
    InputEndpoint endpoint = new InputEndpoint();
    endpointsList.add(endpoint);/*from w w w .  j  a va2 s .c o  m*/
    endpoint.setLocalPort(port);
    endpoint.setPort(port);
    endpoint.setProtocol("TCP");
    endpoint.setName(AzurePropertiesNames.ENDPOINT_NAME);
    final EndpointAcl acl = new EndpointAcl();
    endpoint.setEndpointAcl(acl);
    final URI serverUri = URI.create(serverLocation);
    List<InetAddress> serverAddresses = new ArrayList<InetAddress>();
    try {
        serverAddresses.addAll(Arrays.asList(InetAddress.getAllByName(serverUri.getHost())));
        serverAddresses.add(InetAddress.getLocalHost());
    } catch (UnknownHostException e) {
        LOG.warn("Unable to identify server name ip list", e);
    }
    final ArrayList<AccessControlListRule> aclRules = new ArrayList<AccessControlListRule>();
    acl.setRules(aclRules);
    int order = 1;
    for (final InetAddress address : serverAddresses) {
        if (!(address instanceof Inet4Address)) {
            continue;
        }
        final AccessControlListRule rule = new AccessControlListRule();
        rule.setOrder(order++);
        rule.setAction("Permit");
        rule.setRemoteSubnet(address.getHostAddress() + "/32");
        rule.setDescription("Server");
        aclRules.add(rule);
    }

    retval.add(value);
    return retval;
}

From source file:com.fujitsu.dc.core.rs.cell.MessageODataResource.java

/**
 * To????baseUrl??????./*from   w w w .j av  a 2  s . c o  m*/
 * @param toValue to???
 * @param baseUrl baseUrl
 */
public static void validateToValue(String toValue, String baseUrl) {
    if (toValue == null) {
        return;
    }
    // URL??
    String checkBaseUrl = null;
    String[] uriList = toValue.split(",");
    for (String uriStr : uriList) {
        try {
            URI uri = new URI(uriStr);
            checkBaseUrl = uri.getScheme() + "://" + uri.getHost();
            int port = uri.getPort();
            if (port != -1) {
                checkBaseUrl += ":" + Integer.toString(port);
            }
            checkBaseUrl += "/";
        } catch (URISyntaxException e) {
            log.info(e.getMessage());
            throw DcCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(SentMessage.P_TO.getName());
        }

        if (checkBaseUrl == null || !checkBaseUrl.equals(baseUrl)) {
            throw DcCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(SentMessage.P_TO.getName());
        }
    }

}

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

public static FTPClient getFtpConnection(PublishingProfile pp) throws IOException {

    FTPClient ftp = new FTPClient();

    System.out.println("\t\t" + pp.ftpUrl());
    System.out.println("\t\t" + pp.ftpUsername());
    System.out.println("\t\t" + pp.ftpPassword());

    URI uri = URI.create("ftp://" + pp.ftpUrl());
    ftp.connect(uri.getHost(), 21);
    final int replyCode = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(replyCode)) {
        ftp.disconnect();/*from www. ja v  a  2 s.c  o m*/
        throw new ConnectException("Unable to connect to FTP server");
    }

    if (!ftp.login(pp.ftpUsername(), pp.ftpPassword())) {
        throw new ConnectException("Unable to login to FTP server");
    }

    ftp.setControlKeepAliveTimeout(Constants.connection_read_timeout_ms);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    ftp.enterLocalPassiveMode();//Switch to passive mode

    return ftp;
}

From source file:cn.tiup.httpproxy.ProxyServlet.java

private static String getHost(HttpServletRequest request) {
    StringBuffer requestURL = request.getRequestURL();
    try {//from  w  w  w. j  av  a  2  s .  c  om
        URI uri = new URI(requestURL.toString());
        int port = uri.getPort();
        if (port > 0 && port != 80 && port != 443) {
            return uri.getHost() + ":" + Integer.toString(port);
        } else {
            return uri.getHost();
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return request.getServerName();
}