Example usage for java.net InetSocketAddress getPort

List of usage examples for java.net InetSocketAddress getPort

Introduction

In this page you can find the example usage for java.net InetSocketAddress getPort.

Prototype

public final int getPort() 

Source Link

Document

Gets the port number.

Usage

From source file:io.tourniquet.junit.http.rules.HttpExchangeTest.java

@Test
public void testGetSourceAddress() throws Exception {
    //prepare//from   w w  w.jav  a  2  s  . co  m
    exchange.setSourceAddress(InetSocketAddress.createUnresolved("somehost", 12345));

    //act
    InetSocketAddress source = subject.getSourceAddress();

    //assert
    assertNotNull(source);
    assertEquals("somehost", source.getHostName());
    assertEquals(12345, source.getPort());
}

From source file:org.apache.hadoop.realtime.client.ClientServiceDelegate.java

private DragonClientProtocol getProxy() throws YarnRemoteException {
    if (realProxy != null) {
        return realProxy;
    }/*w  w  w. ja  va 2  s . c o m*/
    ApplicationReport application = rm.getApplicationReport(appId);
    if (application != null) {
        trackingUrl = application.getTrackingUrl();
    }
    String serviceAddr = null;
    while (application == null || YarnApplicationState.RUNNING == application.getYarnApplicationState()) {
        try {
            if (application.getHost() == null || "".equals(application.getHost())) {
                LOG.debug("AM not assigned to Job. Waiting to get the AM ...");
                Thread.sleep(2000);

                LOG.debug("Application state is " + application.getYarnApplicationState());
                application = rm.getApplicationReport(appId);
                continue;
            }
            if (!conf.getBoolean(DragonJobConfig.JOB_AM_ACCESS_DISABLED, false)) {
                UserGroupInformation newUgi = UserGroupInformation
                        .createRemoteUser(UserGroupInformation.getCurrentUser().getUserName());
                serviceAddr = application.getHost() + ":" + application.getRpcPort();
                if (UserGroupInformation.isSecurityEnabled()) {
                    String clientTokenEncoded = application.getClientToken();
                    Token<ApplicationTokenIdentifier> clientToken = new Token<ApplicationTokenIdentifier>();
                    clientToken.decodeFromUrlString(clientTokenEncoded);
                    // RPC layer client expects ip:port as service for tokens
                    InetSocketAddress addr = NetUtils.createSocketAddr(application.getHost(),
                            application.getRpcPort());
                    clientToken.setService(new Text(addr.getAddress().getHostAddress() + ":" + addr.getPort()));
                    newUgi.addToken(clientToken);
                }
                LOG.debug("Connecting to " + serviceAddr);
                final String tempStr = serviceAddr;
                realProxy = newUgi.doAs(new PrivilegedExceptionAction<DragonClientProtocol>() {
                    @Override
                    public DragonClientProtocol run() throws IOException {
                        return instantiateAMProxy(tempStr);
                    }
                });
            } else {
                if (!amAclDisabledStatusLogged) {
                    LOG.info("Network ACL closed to AM for job " + jobId
                            + ". Not going to try to reach the AM.");
                    amAclDisabledStatusLogged = true;
                }
                return getNotRunningJob(null, JobState.RUNNING);
            }
            return realProxy;
        } catch (IOException e) {
            //possibly the AM has crashed
            //there may be some time before AM is restarted
            //keep retrying by getting the address from RM
            LOG.info("Could not connect to " + serviceAddr + ". Waiting for getting the latest AM address...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                LOG.warn("getProxy() call interruped", e1);
                throw new YarnException(e1);
            }
            application = rm.getApplicationReport(appId);
        } catch (InterruptedException e) {
            LOG.warn("getProxy() call interruped", e);
            throw new YarnException(e);
        }
    }

    /** we just want to return if its allocating, so that we don't
     * block on it. This is to be able to return job status
     * on an allocating Application.
     */
    String user = application.getUser();
    if (user == null) {
        throw RPCUtil.getRemoteException("User is not set in the application report");
    }
    if (application.getYarnApplicationState() == YarnApplicationState.NEW
            || application.getYarnApplicationState() == YarnApplicationState.SUBMITTED) {
        realProxy = null;
        return getNotRunningJob(application, JobState.NEW);
    }

    if (application.getYarnApplicationState() == YarnApplicationState.FAILED) {
        realProxy = null;
        return getNotRunningJob(application, JobState.FAILED);
    }

    if (application.getYarnApplicationState() == YarnApplicationState.KILLED) {
        realProxy = null;
        return getNotRunningJob(application, JobState.KILLED);
    }

    return realProxy;
}

From source file:edu.umass.cs.reconfiguration.deprecated.ReconfigurableClient.java

private InetSocketAddress getFirstRCReplica(boolean offset) {
    InetSocketAddress address = this.getReconfigurators().iterator().next();
    return offset
            ? new InetSocketAddress(address.getAddress(), ActiveReplica.getClientFacingPort(address.getPort()))
            : address;/*from  ww w .  j  a v  a 2  s .  co m*/
}

From source file:com.raphfrk.craftproxyclient.net.protocol.p17xlogin.P17xLoginProtocol.java

@Override
public Protocol handleLogin(Handshake handshake, PacketChannel client, PacketChannel server,
        InetSocketAddress serverAddr) throws IOException {
    P17xHandshake h = (P17xHandshake) handshake;

    if (h.getNextState() != 2) {
        sendKick("Unknown handshake next state " + h.getNextState(), client);
        return null;
    }//w  w  w.  jav  a  2s  .  c  o m

    h.setServerPort(serverAddr.getPort());
    h.setServerhost(serverAddr.getHostString());

    server.setRegistry(handshakePacketRegistry);
    server.writePacket(h);
    server.setRegistry(getPacketRegistry());

    int id = client.getPacketId();

    if (this.isKickMessage(id, true)) {
        client.transferPacket(server);
        sendKick("Kick message received from client", client);
        return null;
    } else if (id != 0) {
        sendKick("Expected LoginStart message", client);
        return null;
    }

    P17xLoginStart loginStart = new P17xLoginStart(client.getPacket());

    if (loginStart.getUsername() == null || !loginStart.getUsername().equals(AuthManager.getUsername())) {
        sendKick("Login mismatch, proxy logged as " + AuthManager.getUsername() + " client logged in as "
                + loginStart.getUsername(), client);
        return null;
    }

    server.writePacket(loginStart);

    id = server.getPacketId();
    if (this.isKickMessage(id, false)) {
        server.transferPacket(client);
        return null;
    } else if (id != 0x01 && id != 0x02) {
        sendKick("Expecting Encrypt Key Request or Login Success packet from server, got " + id, client);
        return null;
    }

    if (id == 0x01) {
        P17xEncryptionKeyRequest request = new P17xEncryptionKeyRequest(server.getPacket());

        byte[] secret = Crypt.getBytes(16);

        if (!authSession(secret, client, request)) {
            return null;
        }

        if (!sendEncryptionKeyResponse(secret, client, server, request)) {
            return null;
        }

        enableEncryption(server, client, secret);
    } else {
        setMultiByteChannels(server, client);
    }

    id = server.getPacketId();
    if (this.isKickMessage(id, false)) {
        server.transferPacket(client);
        return null;
    }
    if (id != 0x02) {
        System.out.println("Id is " + id);
        sendKick("Expecting Login Success packet, got " + id, client);
        return null;
    }

    P17xLoginSuccess success = new P17xLoginSuccess(server.getPacket());
    client.writePacket(success);

    return p172Protocol;
}

From source file:com.devoteam.srit.xmlloader.http.bio.BIOSocketServerListener.java

public void run() {
    try {//  w  ww.j a va 2  s .  c o m
        while (true) {
            //
            // Set up HTTP connection
            //
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL,
                    "SocketServerListener secure=", secure, "waiting for a connection on socket");
            Socket socket = serverSocket.accept();
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL,
                    "SocketServerListener secure=", secure, "got a connection");

            DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection();
            HttpParams params = new BasicHttpParams();
            serverConnection.bind(socket, params);

            InetSocketAddress remoteInetSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
            InetSocketAddress localInetSocketAddress = (InetSocketAddress) socket.getLocalSocketAddress();

            String connectionName = "HTTPServerConnection" + Stack.nextTransactionId();
            String remoteHost = remoteInetSocketAddress.getAddress().getHostAddress();
            String remotePort = Integer.toString(remoteInetSocketAddress.getPort());
            String localHost = localInetSocketAddress.getAddress().getHostAddress();
            String localPort = Integer.toString(localInetSocketAddress.getPort());

            BIOChannelHttp connHttp = new BIOChannelHttp(connectionName, localHost, localPort, remoteHost,
                    remotePort, StackFactory.PROTOCOL_HTTP, secure);

            //
            // Start Server thread
            //
            BIOSocketServerHttp socketServerHttp = new BIOSocketServerHttp(serverConnection, connHttp);

            connHttp.setSocketServerHttp(socketServerHttp);
            StackFactory.getStack(StackFactory.PROTOCOL_HTTP).openChannel(connHttp);
        }
    } catch (Exception e) {
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.PROTOCOL, e,
                "Exception in SocketServerListener secure=" + secure);
    }

    GlobalLogger.instance().getApplicationLogger().warn(TextEvent.Topic.PROTOCOL,
            "SocketServerListener secure=", secure, "stopped");
}

From source file:org.apache.hadoop.yarn.factories.impl.pb.RpcServerFactoryPBImpl.java

private Server createServer(Class<?> pbProtocol, InetSocketAddress addr, Configuration conf,
        SecretManager<? extends TokenIdentifier> secretManager, int numHandlers,
        BlockingService blockingService, String portRangeConfig) throws IOException {
    RPC.setProtocolEngine(conf, pbProtocol, ProtobufRpcEngine.class);
    RPC.Server server = new RPC.Builder(conf).setProtocol(pbProtocol).setInstance(blockingService)
            .setBindAddress(addr.getHostName()).setPort(addr.getPort()).setNumHandlers(numHandlers)
            .setVerbose(false).setSecretManager(secretManager).setPortRangeConfig(portRangeConfig).build();
    LOG.info("Adding protocol " + pbProtocol.getCanonicalName() + " to the server");
    server.addProtocol(RPC.RpcKind.RPC_PROTOCOL_BUFFER, pbProtocol, blockingService);
    return server;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestClientRMTokens.java

@Test
public void testShortCircuitRenewCancelWildcardAddress() throws IOException, InterruptedException {
    InetSocketAddress rmAddr = new InetSocketAddress(123);
    InetSocketAddress serviceAddr = NetUtils.createSocketAddr(InetAddress.getLocalHost().getHostName(),
            rmAddr.getPort(), null);
    checkShortCircuitRenewCancel(rmAddr, serviceAddr, true);
}

From source file:com.twitter.finagle.common.zookeeper.ZooKeeperClient.java

/**
 * Creates an unconnected client that will lazily attempt to connect on the first call to
 * {@link #get}.  All successful connections will be authenticated with the given
 * {@code credentials}.//from  w w w.ja  v  a  2s  .c  o m
 *
 * @param sessionTimeout the ZK session timeout
 * @param credentials the credentials to authenticate with
 * @param chrootPath an optional chroot path
 * @param zooKeeperServers the set of servers forming the ZK cluster
 */
public ZooKeeperClient(Duration sessionTimeout, Credentials credentials, Optional<String> chrootPath,
        Iterable<InetSocketAddress> zooKeeperServers) {
    this.sessionTimeoutMs = (int) Preconditions.checkNotNull(sessionTimeout).inMillis();
    this.credentials = Preconditions.checkNotNull(credentials);

    if (chrootPath.isPresent()) {
        PathUtils.validatePath(chrootPath.get());
    }

    Preconditions.checkNotNull(zooKeeperServers);
    Preconditions.checkArgument(!Iterables.isEmpty(zooKeeperServers), "Must present at least 1 ZK server");

    Thread watcherProcessor = new Thread("ZookeeperClient-watcherProcessor") {
        @Override
        public void run() {
            while (true) {
                try {
                    WatchedEvent event = eventQueue.take();
                    for (Watcher watcher : watchers) {
                        watcher.process(event);
                    }
                } catch (InterruptedException e) {
                    /* ignore */ }
            }
        }
    };
    watcherProcessor.setDaemon(true);
    watcherProcessor.start();

    Iterable<String> servers = Iterables.transform(ImmutableSet.copyOf(zooKeeperServers),
            new Function<InetSocketAddress, String>() {
                @Override
                public String apply(InetSocketAddress addr) {
                    return addr.getHostName() + ":" + addr.getPort();
                }
            });
    this.zooKeeperServers = Joiner.on(',').join(servers);
    this.connectString = this.zooKeeperServers.concat(chrootPath.or(""));
}

From source file:edu.umass.cs.msocket.proxy.ProxyGnsPublisher.java

/**
 * Establish a connection with the GNS, register the proxy in the proxy group,
 * start a monitoring socket and register its IP in the GNS,
 * /*from  w  w w.jav  a2  s .c  o  m*/
 * @throws Exception
 */
public void registerProxyInGns() throws Exception {
    logger.info("Looking for proxy " + proxyName + " GUID and certificates...");
    GuidEntry myGuid = KeyPairUtils.getGuidEntryFromPreferences(
            gnsCredentials.getGnsHost() + ":" + gnsCredentials.getGnsPort(), proxyName);

    final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient();
    if (myGuid == null) {
        logger.info("No keys found for proxy " + proxyName + ". Generating new GUID and keys");
        myGuid = gnsClient.guidCreate(gnsCredentials.getGuidEntry(), proxyName);
    }
    logger.info("Proxy has guid " + myGuid.getGuid());

    // Determine our IP
    String sIp = null;
    BufferedReader in;
    InetAddress addr;
    try {
        addr = ((InetSocketAddress) proxySocketAddres).getAddress();
        if (addr != null && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress()
                && !addr.isSiteLocalAddress())
            sIp = addr.getHostAddress();
    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to resolve proxy address " + proxySocketAddres, e);
    }

    if (sIp == null) {
        logger.warning("Local proxy address (" + proxySocketAddres + ") does not seem to be a public address");
        try {
            logger.info("Determining local IP");
            // Determine our external IP address by contacting http://icanhazip.com
            URL whatismyip = new URL("http://icanhazip.com");
            in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
            sIp = in.readLine();
            in.close();
        } catch (Exception e) {
        }
    }

    ProxyInfo proxyInfo = new ProxyInfo(myGuid.getGuid(), proxyName, sIp);

    try {
        // Contact http://freegeoip.net/csv/[IP] to resolve IP address location
        URL locator = new URL("http://freegeoip.net/csv/" + sIp);
        in = new BufferedReader(new InputStreamReader(locator.openStream()));
        String csv = in.readLine();
        in.close();
        // Read location result
        StringTokenizer st = new StringTokenizer(csv, ",");
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read IP");
        st.nextToken(); // IP
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read country code");
        String countryCode = st.nextToken().replace("\"", "");
        proxyInfo.setCountryCode(countryCode);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read country name");
        String countryName = st.nextToken().replace("\"", "");
        proxyInfo.setCountryName(countryName);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read state code");
        String stateCode = st.nextToken().replace("\"", "");
        proxyInfo.setStateCode(stateCode);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read state name");
        String stateName = st.nextToken().replace("\"", "");
        proxyInfo.setStateName(stateName);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read city");
        String city = st.nextToken().replace("\"", "");
        proxyInfo.setCity(city);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read zip");
        String zip = st.nextToken().replace("\"", "");
        proxyInfo.setZipCode(zip);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read latitude");
        String latitudeStr = st.nextToken().replace("\"", "");
        double latitude = Double.parseDouble(latitudeStr);
        if (!st.hasMoreTokens())
            throw new IOException("Failed to read longitude");
        String longitudeStr = st.nextToken().replace("\"", "");
        double longitude = Double.parseDouble(longitudeStr);
        proxyInfo.setLatLong(new GlobalPosition(latitude, longitude, 0));
    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to locate IP address " + e);
    }

    // Look for the group GUID
    String groupGuid = gnsClient.lookupGuid(proxyGroupName);

    // Check if we are a member of the group
    boolean isVerified = false;
    try {
        JSONArray members = gnsClient.groupGetMembers(groupGuid, myGuid);
        for (int i = 0; i < members.length(); i++) {
            if (myGuid.getGuid().equals(members.get(i))) {
                isVerified = true;
                break;
            }
        }
    } catch (Exception e) {
        /*
         * At this point we couldn't get or parse the member list probably because
         * we don't have read access to it. This means we are not a verified
         * member.
         */
        logger.log(Level.INFO,
                "Could not access the proxy group member list because we are not likely a group member yet ("
                        + e + ")");
    }

    // Make sure we advertise ourselves as a proxy and make the field readable
    // by everyone
    gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.SERVICE_TYPE_FIELD,
            new JSONArray().put(GnsConstants.PROXY_SERVICE), myGuid);
    gnsClient.aclAdd(AccessType.READ_WHITELIST, myGuid, GnsConstants.SERVICE_TYPE_FIELD, null);
    // Publish external IP (readable by everyone)
    InetSocketAddress externalIP = (InetSocketAddress) proxySocketAddres;
    gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.PROXY_EXTERNAL_IP_FIELD,
            new JSONArray().put(externalIP.getAddress().getHostAddress() + ":" + externalIP.getPort()), myGuid);
    gnsClient.aclAdd(AccessType.READ_WHITELIST, myGuid, GnsConstants.PROXY_EXTERNAL_IP_FIELD, null);

    // Update our location if geolocation resolution worked
    if (proxyInfo.getLatLong() != null)
        gnsClient.setLocation(proxyInfo.getLatLong().getLongitude(), proxyInfo.getLatLong().getLatitude(),
                myGuid);

    if (!isVerified) {
        logger.log(Level.WARNING,
                "This proxy has not been verified yet, it will stay in the unverified list until it gets added to the proxy group");
    }

    gnsTimer = new GnsTimerKeepalive(gnsCredentials, myGuid, 1000);
    gnsTimer.start();
}

From source file:com.ibasco.agql.core.AbstractMessage.java

protected final CompareToBuilder compareToBuilder(AbstractMessage<T> rhs) {
    final CompareToBuilder builder = new CompareToBuilder();
    InetSocketAddress lhsSender = defaultIfNull(sender(), new InetSocketAddress(0));
    InetSocketAddress rhsSender = defaultIfNull(rhs.sender(), new InetSocketAddress(0));
    InetSocketAddress lhsReciepient = defaultIfNull(recipient(), new InetSocketAddress(0));
    InetSocketAddress rhsReciepient = defaultIfNull(rhs.recipient(), new InetSocketAddress(0));
    builder.append(lhsSender.getAddress().getHostAddress(), rhsSender.getAddress().getHostAddress());
    builder.append(lhsSender.getPort(), rhsSender.getPort());
    builder.append(lhsReciepient.getAddress().getHostAddress(), rhsReciepient.getAddress().getHostAddress());
    builder.append(lhsReciepient.getPort(), rhsReciepient.getPort());
    builder.append(getClass().getSimpleName(), rhs.getClass().getSimpleName());
    return builder;
}