Example usage for com.google.common.net InetAddresses toUriString

List of usage examples for com.google.common.net InetAddresses toUriString

Introduction

In this page you can find the example usage for com.google.common.net InetAddresses toUriString.

Prototype

public static String toUriString(InetAddress ip) 

Source Link

Document

Returns the string representation of an InetAddress suitable for inclusion in a URI.

Usage

From source file:io.airlift.http.server.HttpServerInfo.java

@Inject
public HttpServerInfo(HttpServerConfig config, NodeInfo nodeInfo) {
    if (config.isHttpEnabled()) {
        httpUri = buildUri("http", InetAddresses.toUriString(nodeInfo.getInternalIp()), config.getHttpPort());
        httpExternalUri = buildUri("http", nodeInfo.getExternalAddress(), httpUri.getPort());
    } else {//w  ww. j a va  2  s.co m
        httpUri = null;
        httpExternalUri = null;
    }

    if (config.isHttpsEnabled()) {
        httpsUri = buildUri("https", InetAddresses.toUriString(nodeInfo.getInternalIp()),
                config.getHttpsPort());
        httpsExternalUri = buildUri("https", nodeInfo.getExternalAddress(), httpsUri.getPort());
    } else {
        httpsUri = null;
        httpsExternalUri = null;
    }

    if (config.isAdminEnabled()) {
        if (config.isHttpsEnabled()) {
            adminUri = buildUri("https", InetAddresses.toUriString(nodeInfo.getInternalIp()),
                    config.getAdminPort());
            adminExternalUri = buildUri("https", nodeInfo.getExternalAddress(), adminUri.getPort());
        } else {
            adminUri = buildUri("http", InetAddresses.toUriString(nodeInfo.getInternalIp()),
                    config.getAdminPort());
            adminExternalUri = buildUri("http", nodeInfo.getExternalAddress(), adminUri.getPort());
        }
    } else {
        adminUri = null;
        adminExternalUri = null;
    }
}

From source file:org.elasticsearch.common.network.NetworkAddress.java

static String format(InetAddress address, int port) {
    Objects.requireNonNull(address);

    StringBuilder builder = new StringBuilder();

    if (port != -1 && address instanceof Inet6Address) {
        builder.append(InetAddresses.toUriString(address));
    } else {/*from   w ww  . j a  v a  2s  .  co  m*/
        builder.append(InetAddresses.toAddrString(address));
    }

    if (port != -1) {
        builder.append(':');
        builder.append(port);
    }

    return builder.toString();
}

From source file:com.turn.ttorrent.protocol.tracker.http.HTTPAnnounceRequestMessage.java

@Nonnull
@VisibleForTesting/*from   w w  w .  j a v  a 2 s .c om*/
/* pp */ static String toUrlString(@Nonnull InetAddress address, int port) throws UnsupportedEncodingException {
    String text = InetAddresses.toUriString(address);
    if (port != -1)
        text = text + ":" + port;
    return URLEncoder.encode(text, BEUtils.BYTE_ENCODING_NAME);
}

From source file:fr.letroll.ttorrentandroid.common.protocol.http.HTTPAnnounceRequestMessage.java

@Nonnull
@VisibleForTesting//from ww w  .  j a v  a 2  s  .  co m
/* pp */ static String toUrlString(@Nonnull InetAddress address, int port) throws UnsupportedEncodingException {
    String text = InetAddresses.toUriString(address);
    if (port != -1)
        text = text + ":" + port;
    return URLEncoder.encode(text, Torrent.BYTE_ENCODING_NAME);
}

From source file:com.turn.ttorrent.tracker.Tracker.java

/**
 * Returns the full announce URL served by this tracker.
 *
 * <p>/*from  w w  w  . j a  v a  2s.c  o  m*/
 * This has the form http://ip:port/announce.
 * </p>
 */
@CheckForNull
public URL getAnnounceUrl() {
    try {
        InetSocketAddress listenAddress = getListenAddress();
        return new URL("http", InetAddresses.toUriString(listenAddress.getAddress()), listenAddress.getPort(),
                Tracker.ANNOUNCE_URL);
    } catch (MalformedURLException e) {
        LOG.error("Could not build tracker URL: " + e, e);
    }

    return null;
}

From source file:com.turn.ttorrent.tracker.simple.SimpleTracker.java

/**
 * Returns the full announce URL served by this tracker.
 *
 * <p>//from www  . j  av  a2s.c  om
 * This has the form http://ip:port/announce.
 * </p>
 */
@Nonnull
public List<URL> getAnnounceUrls() throws SocketException {
    List<URL> out = new ArrayList<URL>();
    for (InetSocketAddress address : getListenAddresses()) {
        try {
            out.add(new URL("http", InetAddresses.toUriString(address.getAddress()), address.getPort(),
                    TrackerUtils.DEFAULT_ANNOUNCE_URL));
        } catch (MalformedURLException e) {
            LOG.error("Could not build tracker URL from " + address, e);
        }
    }
    return out;
}

From source file:fr.letroll.ttorrentandroid.tracker.Tracker.java

/**
 * Returns the full announce URL served by this tracker.
 *
 * <p>/*from ww  w .ja  va 2  s.  c  o m*/
 * This has the form http://ip:port/announce.
 * </p>
 */
@Nonnull
public List<URL> getAnnounceUrls() throws SocketException {
    List<URL> out = new ArrayList<URL>();
    for (InetSocketAddress address : getListenAddresses()) {
        try {
            out.add(new URL("http", InetAddresses.toUriString(address.getAddress()), address.getPort(),
                    Tracker.ANNOUNCE_URL));
        } catch (MalformedURLException e) {
            LOG.error("Could not build tracker URL from " + address, e);
        }
    }
    return out;
}

From source file:org.dcache.xrootd.door.XrootdRedirectHandler.java

/**
 * For client-server read and write, the open, if successful, will always
 * result in a redirect response to the proper pool; hence no subsequent
 * requests like sync, read, write or close are expected at the door.
 *
 * For third-party copy where dCache is the source, the interactions are as
 * follows:/*from w  w w.j a  va 2s  .  c  o m*/
 *
 * 1.  The client opens the file to check availability (the 'placement'
 *     stage).  An OK response is followed by the client closing the file.
 * 2.  The client opens the file again with rendezvous metadata.  The
 *     client will close the file only when notified by the destination
 *     server that the transfer has completed.
 * 3.  The destination server will open the file for the actual read.
 *
 * The order of 2, 3 is not deterministic; hence the response here must
 * provide for the possibility that the destination server attempts an
 * open before the client specifies a time-to-live on the rendezvous
 * point.
 *
 * The strategy adopted is therefore as follows:  response to (1) is simply
 * to check file permissions.  No metadata is generated and a "dummy"
 * file handle is returned.  For 2 and 3, whichever occurs first
 * will cause a metadata object to be stored.  If the destination server
 * open occurs first, a wait response will tell the server to try again
 * in a maximum of 3 seconds; otherwise, if the request matches and occurs
 * within the ttl, the mover will be started and the destination
 * redirected to the pool. Response to the client will carry a file
 * handle but will not actually open a mover.  The close from the client
 * is handled at the door by removing the rendezvous information.
 *
 * Third-party copy where dCache is the destination should proceed with
 * the usual upload transfer creation, but when the client is redirected
 * to the pool and calls kXR_open there, a third-party client will
 * be started which does read requests from the source and then writes
 * the data to the mover channel.
 */
@Override
protected XrootdResponse<OpenRequest> doOnOpen(ChannelHandlerContext ctx, OpenRequest req)
        throws XrootdException {
    /*
     * TODO
     *
     * We ought to process this asynchronously to not block the calling thread during
     * staging or queuing. We should also switch to an asynchronous reply model if
     * the request is nearline or is queued on a pool. The naive approach to always
     * use an asynchronous reply model doesn't work because the xrootd 3.x client
     * introduces an artificial 1 second delay when processing such a response.
     */

    InetSocketAddress localAddress = getDestinationAddress();
    InetSocketAddress remoteAddress = getSourceAddress();

    Map<String, String> opaque;

    try {
        opaque = OpaqueStringParser.getOpaqueMap(req.getOpaque());
        if (opaque.isEmpty()) {
            /*
             * create a new HashMap as empty opaque map is immutable
             */
            opaque = new HashMap<>();
        }
    } catch (ParseException e) {
        _log.warn("Ignoring malformed open opaque {}: {}", req.getOpaque(), e.getMessage());
        opaque = new HashMap<>();
    }

    try {
        FsPath path = createFullPath(req.getPath());

        XrootdResponse response = conditionallyHandleThirdPartyRequest(req, opaque, path,
                remoteAddress.getHostName());
        if (response != null) {
            return response;
        }

        FilePerm neededPerm = req.getRequiredPermission();

        _log.info("Opening {} for {}", req.getPath(), neededPerm.xmlText());
        if (_log.isDebugEnabled()) {
            logDebugOnOpen(req);
        }

        String ioQueue = appSpecificQueue(req);

        Long size = null;
        try {
            String value = opaque.get("oss.asize");
            if (value != null) {
                size = Long.valueOf(value);
            }
        } catch (NumberFormatException exception) {
            _log.warn("Ignoring malformed oss.asize: {}", exception.getMessage());
        }

        UUID uuid = UUID.randomUUID();
        opaque.put(UUID_PREFIX, uuid.toString());
        /*
         *  In case this is a third-party open as destination,
         *  pass the client information to the pool.
         */
        opaque.put("org.dcache.xrootd.client", getTpcClientId(req.getSession()));
        String opaqueString = OpaqueStringParser.buildOpaqueString(opaque);

        /*
         * Interact with core dCache to open the requested file.
         */
        XrootdTransfer transfer;
        if (neededPerm == FilePerm.WRITE) {
            boolean createDir = req.isMkPath();
            boolean overwrite = req.isDelete() && !req.isNew();
            boolean persistOnSuccessfulClose = (req.getOptions()
                    & XrootdProtocol.kXR_posc) == XrootdProtocol.kXR_posc;
            // TODO: replace with req.isPersistOnSuccessfulClose() with the latest xrootd4j

            transfer = _door.write(remoteAddress, path, ioQueue, uuid, createDir, overwrite, size,
                    _maximumUploadSize, localAddress, req.getSubject(), _authz, persistOnSuccessfulClose,
                    ((_isLoggedIn) ? _userRootPath : _rootPath), req.getSession().getDelegatedCredential());
        } else {
            /*
             * If this is a tpc transfer, then dCache is source here.
             *
             * Since we accept (from the destination server) any
             * valid form of authentication, but without requiring
             * the associated user to be mapped, we can override
             * file permission restrictions (since we possess the
             * 'token' rendezvous key, and the client file permissions
             * have been checked during its open request).
             */
            Subject subject;

            if (opaque.get("tpc.key") == null) {
                subject = req.getSubject();
            } else {
                subject = Subjects.ROOT;
            }

            transfer = _door.read(remoteAddress, path, ioQueue, uuid, localAddress, subject, _authz);

            /*
             * Again, if this is a tpc transfer, then dCache is source here.
             * The transfer is initiated by the destination server
             * (= current session).  However, we wish the doorinfo
             * client in billing to reflect the original user connection,
             * so we overwrite the transfer client address, which
             * is unused by the mover.
             */
            String client = opaque.get("tpc.org");
            if (client != null) {
                int index = client.indexOf("@");
                if (index != -1 && index < client.length() - 1) {
                    client = client.substring(index + 1);
                    transfer.setClientAddress(new InetSocketAddress(client, 0));
                }
            }
        }

        // ok, open was successful
        InetSocketAddress address = transfer.getRedirect();
        _log.info("Redirecting to {}", address);

        /* xrootd developers say that IPv6 addresses must always be URI quoted.
         * The spec doesn't require this, but clients depend on it.
         */
        return new RedirectResponse<>(req, InetAddresses.toUriString(address.getAddress()), address.getPort(),
                opaqueString, "");
    } catch (FileNotFoundCacheException e) {
        return withError(req, kXR_NotFound, "No such file");
    } catch (FileExistsCacheException e) {
        return withError(req, kXR_NotAuthorized, "File already exists");
    } catch (TimeoutCacheException e) {
        return withError(req, kXR_ServerError, "Internal timeout");
    } catch (PermissionDeniedCacheException e) {
        return withError(req, kXR_NotAuthorized, e.getMessage());
    } catch (FileIsNewCacheException e) {
        return withError(req, kXR_FileLocked, "File is locked by upload");
    } catch (NotFileCacheException e) {
        return withError(req, kXR_NotFile, "Not a file");
    } catch (CacheException e) {
        return withError(req, kXR_ServerError,
                String.format("Failed to open file (%s [%d])", e.getMessage(), e.getRc()));
    } catch (InterruptedException e) {
        /* Interrupt may be caused by cell shutdown or client
         * disconnect.  If the client disconnected, then the error
         * message will never reach the client, so saying that the
         * server shut down is okay.
         */
        return withError(req, kXR_ServerError, "Server shutdown");
    }
}

From source file:com.pidoco.juri.JURI.java

/**
 * Does not attempt name resolution (and therefore does not block).
 *
 * @param address to set as hostname. Works with both ipv4 and ipv6 addresses. ipv4 addresses in ipv6 form are
 *                set as ipv6 address. A given ipv4 address is not converted into an ipv6 address.
 * @param useHostIfAvailable if true, checks if the address has a known hostname
 *                           and uses that name instead of the address. Consider using {@link #setHost(String)}}
 *                           directly instead.
 *                           No name resolution is performed at the penalty of additional string concatenation
 *                           when using {@link InetAddress#toString()}.
 *//*from w  ww  . ja  va2  s. c  om*/
public JURI setHost(@Nullable InetAddress address, boolean useHostIfAvailable) {
    if (address == null) {
        return setHost("");
    }

    if (useHostIfAvailable && checkIfAddressHasHostnameWithoutNameLookup(address)) {
        this.setHost(address.getHostName());
    } else {
        this.setHost(InetAddresses.toUriString(address));
    }
    return this;
}

From source file:com.google.devtools.build.lib.server.GrpcServerImpl.java

@Override
public void serve() throws IOException {
    Preconditions.checkState(!serving);//  w  w w . j  a  v a  2 s .com

    // For reasons only Apple knows, you cannot bind to IPv4-localhost when you run in a sandbox
    // that only allows loopback traffic, but binding to IPv6-localhost works fine. This would
    // however break on systems that don't support IPv6. So what we'll do is to try to bind to IPv6
    // and if that fails, try again with IPv4.
    InetSocketAddress address = new InetSocketAddress("[::1]", port);
    try {
        server = NettyServerBuilder.forAddress(address).addService(commandServer).directExecutor().build()
                .start();
    } catch (IOException e) {
        address = new InetSocketAddress("127.0.0.1", port);
        server = NettyServerBuilder.forAddress(address).addService(commandServer).directExecutor().build()
                .start();
    }

    if (maxIdleSeconds > 0) {
        Thread timeoutThread = new Thread(new Runnable() {
            @Override
            public void run() {
                timeoutThread();
            }
        });

        timeoutThread.setName("grpc-timeout");
        timeoutThread.setDaemon(true);
        timeoutThread.start();
    }
    serving = true;

    writeServerFile(PORT_FILE, InetAddresses.toUriString(address.getAddress()) + ":" + server.getPort());
    writeServerFile(REQUEST_COOKIE_FILE, requestCookie);
    writeServerFile(RESPONSE_COOKIE_FILE, responseCookie);

    try {
        server.awaitTermination();
    } catch (InterruptedException e) {
        // TODO(lberki): Handle SIGINT in a reasonable way
        throw new IllegalStateException(e);
    }
}