Example usage for com.google.common.net HostAndPort fromString

List of usage examples for com.google.common.net HostAndPort fromString

Introduction

In this page you can find the example usage for com.google.common.net HostAndPort fromString.

Prototype

public static HostAndPort fromString(String hostPortString) 

Source Link

Document

Split a freeform string into a host and port, without strict validation.

Usage

From source file:com.yahoo.omid.tsoclient.TSOClientImpl.java

private HostAndPort getCurrentTSOHostAndPortFoundInZK() throws ZKException {
    ChildData currentTSOData = currentTSOZNode.getCurrentData();
    if (currentTSOData == null) {
        throw new ZKException("No ZKNode found " + CURRENT_TSO_PATH);
    }/*from  w w  w. j a v a  2 s .  c om*/
    byte[] currentTSOAsBytes = currentTSOData.getData();
    if (currentTSOAsBytes == null) {
        throw new ZKException("No data found for current TSO in ZKNode " + CURRENT_TSO_PATH);
    }
    String currentTSO = new String(currentTSOAsBytes, Charsets.UTF_8);
    HostAndPort hp = HostAndPort.fromString(currentTSO);
    return hp;
}

From source file:org.apache.accumulo.gc.replication.CloseWriteAheadLogReferences.java

private HostAndPort getMasterAddress() {
    try {//w w  w .j av  a 2  s  .c  o m
        List<String> locations = context.getInstance().getMasterLocations();
        if (locations.size() == 0)
            return null;
        return HostAndPort.fromString(locations.get(0));
    } catch (Exception e) {
        log.warn("Failed to obtain master host " + e);
    }

    return null;
}

From source file:com.google.cloud.GrpcServiceOptions.java

/**
 * Returns a channel provider.//from   w  ww.  j a v a 2 s  . co  m
 */
protected ChannelProvider getChannelProvider() {
    HostAndPort hostAndPort = HostAndPort.fromString(getHost());
    InstantiatingChannelProvider.Builder builder = InstantiatingChannelProvider.newBuilder()
            .setServiceAddress(hostAndPort.getHostText()).setPort(hostAndPort.getPort())
            .setClientLibHeader(getGoogApiClientLibName(), firstNonNull(getLibraryVersion(), ""));
    Credentials scopedCredentials = getScopedCredentials();
    if (scopedCredentials != null && scopedCredentials != NoCredentials.getInstance()) {
        builder.setCredentialsProvider(FixedCredentialsProvider.create(scopedCredentials));
    }
    return builder.build();
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void doHandle(HttpServletRequest request, HttpServletResponse response)
        throws IOException, S3Exception {
    String method = request.getMethod();
    String uri = request.getRequestURI();
    logger.debug("request: {}", request);
    String hostHeader = request.getHeader(HttpHeaders.HOST);
    if (hostHeader != null && virtualHost.isPresent()) {
        hostHeader = HostAndPort.fromString(hostHeader).getHostText();
        String virtualHostSuffix = "." + virtualHost.get();
        if (!hostHeader.equals(virtualHost.get())) {
            if (hostHeader.endsWith(virtualHostSuffix)) {
                String bucket = hostHeader.substring(0, hostHeader.length() - virtualHostSuffix.length());
                uri = "/" + bucket + uri;
            } else {
                String bucket = hostHeader.toLowerCase();
                uri = "/" + bucket + uri;
            }//  w w  w.j  ava  2 s . c om
        }
    }

    boolean hasDateHeader = false;
    boolean hasXAmzDateHeader = false;
    for (String headerName : Collections.list(request.getHeaderNames())) {
        for (String headerValue : Collections.list(request.getHeaders(headerName))) {
            logger.trace("header: {}: {}", headerName, Strings.nullToEmpty(headerValue));
        }
        if (headerName.equalsIgnoreCase(HttpHeaders.DATE)) {
            hasDateHeader = true;
        } else if (headerName.equalsIgnoreCase("x-amz-date")) {
            hasXAmzDateHeader = true;
        }
    }

    // anonymous request
    if (method.equals("GET") && request.getHeader(HttpHeaders.AUTHORIZATION) == null
            && request.getParameter("AWSAccessKeyId") == null && defaultBlobStore != null) {
        doHandleAnonymous(request, response, uri, defaultBlobStore);
        return;
    }

    if (!anonymousIdentity && !hasDateHeader && !hasXAmzDateHeader && request.getParameter("Expires") == null) {
        throw new S3Exception(S3ErrorCode.ACCESS_DENIED,
                "AWS authentication requires a valid Date or" + " x-amz-date header");
    }

    // TODO: apply sanity checks to X-Amz-Date
    if (hasDateHeader) {
        long date;
        try {
            date = request.getDateHeader(HttpHeaders.DATE);
        } catch (IllegalArgumentException iae) {
            throw new S3Exception(S3ErrorCode.ACCESS_DENIED, iae);
        }
        if (date < 0) {
            throw new S3Exception(S3ErrorCode.ACCESS_DENIED);
        }
        long now = System.currentTimeMillis();
        if (now + TimeUnit.DAYS.toMillis(1) < date || now - TimeUnit.DAYS.toMillis(1) > date) {
            throw new S3Exception(S3ErrorCode.REQUEST_TIME_TOO_SKEWED);
        }
    }

    BlobStore blobStore;
    String requestIdentity = null;
    String requestSignature = null;
    String headerAuthorization = request.getHeader(HttpHeaders.AUTHORIZATION);

    if (headerAuthorization != null) {
        if (headerAuthorization.startsWith("AWS ")) {
            int colon = headerAuthorization.lastIndexOf(':', headerAuthorization.length() - 2);
            if (colon < 4) {
                throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
            }
            requestIdentity = headerAuthorization.substring(4, colon);
            requestSignature = headerAuthorization.substring(colon + 1);
        } else if (headerAuthorization.startsWith("AWS4-HMAC-SHA256 ")) {
            // Fail V4 signature requests to allow clients to retry with V2.
            throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
        }
    } else {
        requestIdentity = request.getParameter("AWSAccessKeyId");
        requestSignature = request.getParameter("Signature");
    }

    String[] path = uri.split("/", 3);
    for (int i = 0; i < path.length; i++) {
        path[i] = URLDecoder.decode(path[i], "UTF-8");
    }

    Map.Entry<String, BlobStore> provider = blobStoreLocator.locateBlobStore(requestIdentity,
            path.length > 1 ? path[1] : null, path.length > 2 ? path[2] : null);
    if (requestIdentity != null) {
        if (provider == null) {
            throw new S3Exception(S3ErrorCode.INVALID_ACCESS_KEY_ID);
        }

        String expectedSignature = createAuthorizationSignature(request, uri, requestIdentity,
                provider.getKey());
        if (!expectedSignature.equals(requestSignature)) {
            throw new S3Exception(S3ErrorCode.SIGNATURE_DOES_NOT_MATCH);
        }

        blobStore = provider.getValue();

        String expiresString = request.getParameter("Expires");
        if (expiresString != null) {
            long expires = Long.parseLong(expiresString);
            long nowSeconds = System.currentTimeMillis() / 1000;
            if (nowSeconds > expires) {
                throw new S3Exception(S3ErrorCode.ACCESS_DENIED);
            }
        }
    } else {
        if (!anonymousIdentity) {
            throw new S3Exception(S3ErrorCode.ACCESS_DENIED);
        } else {
            blobStore = provider.getValue();
        }
    }

    // emit NotImplemented for unknown parameters
    for (String parameter : Collections.list(request.getParameterNames())) {
        if (!SUPPORTED_PARAMETERS.contains(parameter)) {
            logger.error("Unknown parameters {} with URI {}", parameter, request.getRequestURI());
            throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
        }
    }

    String uploadId = request.getParameter("uploadId");
    switch (method) {
    case "DELETE":
        if (path.length <= 2 || path[2].isEmpty()) {
            handleContainerDelete(response, blobStore, path[1]);
            return;
        } else if (uploadId != null) {
            handleAbortMultipartUpload(request, response, blobStore, path[1], path[2], uploadId);
            return;
        } else {
            handleBlobRemove(response, blobStore, path[1], path[2]);
            return;
        }
    case "GET":
        if (uri.equals("/")) {
            handleContainerList(response, blobStore);
            return;
        } else if (path.length <= 2 || path[2].isEmpty()) {
            if ("".equals(request.getParameter("acl"))) {
                handleGetContainerAcl(response, blobStore, path[1]);
                return;
            } else if ("".equals(request.getParameter("location"))) {
                handleContainerLocation(response, blobStore, path[1]);
                return;
            } else if ("".equals(request.getParameter("uploads"))) {
                handleListMultipartUploads(response, blobStore, uploadId);
                return;
            }
            handleBlobList(request, response, blobStore, path[1]);
            return;
        } else {
            if ("".equals(request.getParameter("acl"))) {
                handleGetBlobAcl(response, blobStore, path[1], path[2]);
                return;
            } else if (uploadId != null) {
                handleListParts(request, response, blobStore, path[1], path[2], uploadId);
                return;
            }
            handleGetBlob(request, response, blobStore, path[1], path[2]);
            return;
        }
    case "HEAD":
        if (path.length <= 2 || path[2].isEmpty()) {
            handleContainerExists(response, blobStore, path[1]);
            return;
        } else {
            handleBlobMetadata(response, blobStore, path[1], path[2]);
            return;
        }
    case "POST":
        if ("".equals(request.getParameter("delete"))) {
            handleMultiBlobRemove(request, response, blobStore, path[1]);
            return;
        } else if ("".equals(request.getParameter("uploads"))) {
            handleInitiateMultipartUpload(request, response, blobStore, path[1], path[2]);
            return;
        } else if (uploadId != null) {
            handleCompleteMultipartUpload(request, response, blobStore, path[1], path[2], uploadId);
            return;
        }
        break;
    case "PUT":
        if (path.length <= 2 || path[2].isEmpty()) {
            if ("".equals(request.getParameter("acl"))) {
                handleSetContainerAcl(request, response, blobStore, path[1]);
                return;
            }
            handleContainerCreate(request, response, blobStore, path[1]);
            return;
        } else if (uploadId != null) {
            handleUploadPart(request, response, blobStore, path[1], path[2], uploadId);
            return;
        } else if (request.getHeader("x-amz-copy-source") != null) {
            handleCopyBlob(request, response, blobStore, path[1], path[2]);
            return;
        } else {
            if ("".equals(request.getParameter("acl"))) {
                handleSetBlobAcl(request, response, blobStore, path[1], path[2]);
                return;
            }
            handlePutBlob(request, response, blobStore, path[1], path[2]);
            return;
        }
    default:
        break;
    }
    logger.error("Unknown method {} with URI {}", method, request.getRequestURI());
    throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
}

From source file:org.apache.brooklyn.location.basic.WinRmMachineLocation.java

@Override
public void init() {
    super.init();

    // Register any pre-existing port-mappings with the PortForwardManager
    Map<Integer, String> tcpPortMappings = getConfig(TCP_PORT_MAPPINGS);
    if (tcpPortMappings != null) {
        PortForwardManager pfm = (PortForwardManager) getManagementContext().getLocationRegistry()
                .resolve("portForwardManager(scope=global)");
        for (Map.Entry<Integer, String> entry : tcpPortMappings.entrySet()) {
            int targetPort = entry.getKey();
            HostAndPort publicEndpoint = HostAndPort.fromString(entry.getValue());
            if (!publicEndpoint.hasPort()) {
                throw new IllegalArgumentException("Invalid portMapping ('" + entry.getValue() + "') for port "
                        + targetPort + " in machine " + this);
            }/*w w w .ja v  a  2s  .  co m*/
            pfm.associate(publicEndpoint.getHostText(), publicEndpoint, this, targetPort);
        }
    }
}

From source file:org.apache.brooklyn.location.byon.ByonLocationResolver.java

private UserAndHostAndPort parseUserAndHostAndPort(String val) {
    String userPart = null;//from   w w  w . ja  v a 2s.  c  om
    String hostPart = val;
    if (val.contains("@")) {
        userPart = val.substring(0, val.indexOf("@"));
        hostPart = val.substring(val.indexOf("@") + 1);
    }
    return UserAndHostAndPort.fromParts(userPart, HostAndPort.fromString(hostPart));
}

From source file:org.apache.omid.tso.client.TSOClient.java

@Override
public void nodeChanged() throws Exception {

    String tsoInfo = getCurrentTSOInfoFoundInZK(zkCurrentTsoPath);
    // TSO info includes the new TSO host:port address and epoch
    String[] currentTSOAndEpochArray = tsoInfo.split("#");
    HostAndPort hp = HostAndPort.fromString(currentTSOAndEpochArray[0]);
    setTSOAddress(hp.getHostText(), hp.getPort());
    epoch = Long.parseLong(currentTSOAndEpochArray[1]);
    LOG.info("CurrentTSO ZNode changed. New TSO Host & Port {}/Epoch {}", hp, getEpoch());
    if (currentChannel != null && currentChannel.isConnected()) {
        LOG.info("\tClosing channel with previous TSO {}", currentChannel);
        currentChannel.close();//from  w  w w  . ja v a  2  s  . c  om
    }

}

From source file:org.voltdb.utils.MiscUtils.java

/**
 * @param server String containing a hostname/ip, or a hostname/ip:port.
 * @param defaultPort If a port isn't specified, use this one.
 * @return hostname or textual ip representation.
 *//*from  www . jav  a2 s  .  c  o  m*/
public static String getHostnameFromHostnameColonPort(String server) {
    return HostAndPort.fromString(server).getHostText();
}

From source file:org.voltdb.utils.MiscUtils.java

/**
 * @param server String containing a hostname/ip, or a hostname/ip:port.
 * @param defaultPort If a port isn't specified, use this one.
 * @return port number.//from  w w  w .  ja va  2s  . com
 */
public static int getPortFromHostnameColonPort(String server, int defaultPort) {
    return HostAndPort.fromString(server).getPortOrDefault(defaultPort);
}

From source file:org.apache.brooklyn.core.network.AbstractOnNetworkEnricher.java

protected boolean isHostAndPort(Object sensorVal) {
    if (sensorVal instanceof HostAndPort) {
        return true;
    } else if (sensorVal instanceof String) {
        try {/*w  w w .  ja  va 2s. c  o  m*/
            HostAndPort hostAndPort = HostAndPort.fromString((String) sensorVal);
            return hostAndPort.hasPort();
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
    return false;
}