Example usage for java.net InetSocketAddress getAddress

List of usage examples for java.net InetSocketAddress getAddress

Introduction

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

Prototype

public final InetAddress getAddress() 

Source Link

Document

Gets the InetAddress .

Usage

From source file:org.pepstock.jem.node.swarm.Swarm.java

/**
 * Initializes the nodeInfo that will be store in the SWARM NODES MAP
 * /*w w  w .ja  v a  2 s  .  c  o  m*/
 * @see org.pepstock.jem.gwt.server.swarm.SwarmQueues#NODES_MAP
 * @param member this hazelcast member of the swarm environment
 */
private void initNodeInfo(Member member) {
    // set uuid of member of hazelcast as key
    nodeInfo.setKey(member.getUuid());
    // set port and ip address
    InetSocketAddress address = member.getInetSocketAddress();
    nodeInfo.setPort(address.getPort());
    nodeInfo.setIpaddress(address.getAddress().getHostAddress());
    // sets label to be displayed by GRS
    nodeInfo.setLabel(nodeInfo.getIpaddress() + ":" + nodeInfo.getPort());
    // use JMX to extract current process id
    nodeInfo.setProcessId(ManagementFactory.getRuntimeMXBean().getName());
    // set hostname
    String hostname = StringUtils.substringAfter(nodeInfo.getProcessId(), "@");
    nodeInfo.setHostname(hostname);
    OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
    nodeInfo.getNodeInfoBean().setSystemArchitecture(bean.getArch());
    nodeInfo.getNodeInfoBean().setAvailableProcessors(bean.getAvailableProcessors());
    nodeInfo.getNodeInfoBean().setSystemName(bean.getName());
    ExecutionEnvironment executionEnvironment = new ExecutionEnvironment();
    // the environment will be that of jem one not the swarm one.
    executionEnvironment.setEnvironment(Main.EXECUTION_ENVIRONMENT.getEnvironment());
    nodeInfo.setExecutionEnvironment(executionEnvironment);
    nodeInfo.setJemVersion(Main.getNode().getJemVersion());
}

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;
}

From source file:org.kde.kdeconnect.LanLinkTest.java

public void testSendPayload() throws Exception {

    class Downloader extends Thread {

        NetworkPackage np;//w  ww.  j a  v  a2  s  . c om
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        public void setNetworkPackage(NetworkPackage networkPackage) {
            this.np = networkPackage;
        }

        public ByteArrayOutputStream getOutputStream() {
            return outputStream;
        }

        @Override
        public void run() {
            try {

                Socket socket = null;
                try {
                    socket = new Socket();
                    int tcpPort = np.getPayloadTransferInfo().getInt("port");
                    InetSocketAddress address = (InetSocketAddress) session.getRemoteAddress();
                    socket.connect(new InetSocketAddress(address.getAddress(), tcpPort));
                    np.setPayload(socket.getInputStream(), np.getPayloadSize());
                } catch (Exception e) {
                    try {
                        socket.close();
                    } catch (Exception ignored) {
                        throw ignored;
                    }
                    e.printStackTrace();
                    Log.e("KDE/LanLinkTest", "Exception connecting to remote socket");
                    throw e;
                }

                final InputStream input = np.getPayload();
                final long fileLength = np.getPayloadSize();

                byte data[] = new byte[1024];
                long progress = 0, prevProgressPercentage = 0;
                int count;
                while ((count = input.read(data)) >= 0) {
                    progress += count;
                    outputStream.write(data, 0, count);
                    if (fileLength > 0) {
                        if (progress >= fileLength)
                            break;
                        long progressPercentage = (progress * 100 / fileLength);
                        if (progressPercentage != prevProgressPercentage) {
                            prevProgressPercentage = progressPercentage;
                        }
                    }

                }
                outputStream.close();
                input.close();

            } catch (Exception e) {
                Log.e("Downloader Test", "Exception");
                e.printStackTrace();
            }
        }
    }

    final Downloader downloader = new Downloader();

    // Using byte array for payload, try to use input stream as used in real device
    String dataString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
            + " Cras vel erat et ante fringilla tristique. Sed consequat ligula at interdum "
            + "rhoncus. Integer semper enim felis, id sodales tellus aliquet eget."
            + " Sed fringilla ac metus eget dictum. Aliquam euismod non sem sit"
            + " amet dapibus. Interdum et malesuada fames ac ante ipsum primis "
            + "in faucibus. Nam et ligula placerat, varius justo eu, convallis "
            + "lorem. Nam consequat consequat tortor et gravida. Praesent "
            + "ultricies tortor eget ex elementum gravida. Suspendisse aliquet "
            + "erat a orci feugiat dignissim.";

    // reallyLongString contains dataString 16 times
    String reallyLongString = dataString + dataString;
    reallyLongString = reallyLongString + reallyLongString;
    reallyLongString = reallyLongString + reallyLongString;
    reallyLongString = reallyLongString + reallyLongString;

    final byte[] data = reallyLongString.getBytes();

    final JSONObject sharePackageJson = new JSONObject(
            "{\"id\":123,\"body\":{\"filename\":\"data.txt\"},\"payloadTransferInfo\":{},\"payloadSize\":8720,\"type\":\"kdeconnect.share\"}");

    // Mocking share package
    final NetworkPackage sharePackage = Mockito.mock(NetworkPackage.class);
    Mockito.when(sharePackage.getType()).thenReturn("kdeconnect.share");
    Mockito.when(sharePackage.hasPayload()).thenReturn(true);
    Mockito.when(sharePackage.hasPayloadTransferInfo()).thenReturn(true);
    Mockito.doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            return sharePackageJson.toString();
        }
    }).when(sharePackage).serialize();
    Mockito.when(sharePackage.getPayload()).thenReturn(new ByteArrayInputStream(data));
    Mockito.when(sharePackage.getPayloadSize()).thenReturn((long) data.length);
    Mockito.doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            return sharePackageJson.getJSONObject("payloadTransferInfo");
        }
    }).when(sharePackage).getPayloadTransferInfo();
    Mockito.doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            JSONObject object = (JSONObject) invocationOnMock.getArguments()[0];

            sharePackageJson.put("payloadTransferInfo", object);
            return null;
        }
    }).when(sharePackage).setPayloadTransferInfo(Mockito.any(JSONObject.class));

    Mockito.doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {

            String stringNetworkPackage = (String) invocationOnMock.getArguments()[0];
            final NetworkPackage np = NetworkPackage.unserialize(stringNetworkPackage);

            downloader.setNetworkPackage(np);
            downloader.start();

            return writeFutureSuccess;
        }
    }).when(session).write(Mockito.anyString());

    lanLink.sendPackage(sharePackage, callback);

    try {
        // Wait 1 secs for downloader to finish (if some error, it will continue and assert will fail)
        downloader.join(1 * 1000);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    assertEquals(new String(data), new String(downloader.getOutputStream().toByteArray()));

}

From source file:org.commoncrawl.io.NIOClientTCPSocket.java

public NIOClientTCPSocket(InetSocketAddress localAddress, NIOClientSocketListener socketListener)
        throws IOException {
    _socketType = SocketType.Outgoing;//  ww w  . j  a  v a  2 s  .c om
    _channel = SocketChannel.open();
    if (localAddress != null) {
        InetSocketAddress modifiedLocalAddress = new InetSocketAddress(localAddress.getAddress(), 0);
        // System.out.println("Binding To Local Address:" +
        // modifiedLocalAddress.getAddress());
        // LOG.info(this + "Binding To Local Address:" +
        // modifiedLocalAddress.getAddress());
        _channel.socket().bind(modifiedLocalAddress);
    }
    _localAddress = (InetSocketAddress) _channel.socket().getLocalSocketAddress();
    setClientSocketOptions(_channel);
    _listener = socketListener;

}

From source file:org.jolokia.jvmagent.handler.JolokiaHttpHandlerTest.java

@Test
public void restrictorWithReverseDnsLookup() throws URISyntaxException, IOException, ParseException {
    Configuration config = getConfig(ConfigKey.RESTRICTOR_CLASS, TestReverseDnsLookupRestrictor.class.getName(),
            ConfigKey.ALLOW_DNS_REVERSE_LOOKUP, "true");
    InetSocketAddress address = new InetSocketAddress(8080);
    TestReverseDnsLookupRestrictor.expectedRemoteHostsToCheck = new String[] { address.getHostName(),
            address.getAddress().getHostAddress() };
    JSONObject resp = simpleMemoryGetReadRequest(config);
    assertFalse(resp.containsKey("error"));
}

From source file:com.bitbreeds.webrtc.signaling.BindingService.java

public byte[] processBindingRequest(byte[] data, String userName, String password, InetSocketAddress sender) {

    logger.trace("Input: " + Hex.encodeHexString(data));

    StunMessage msg = StunMessage.fromBytes(data);

    logger.trace("InputParsed: " + msg);

    byte[] content = SignalUtil.joinBytesArrays(SignalUtil.twoBytesFromInt(0x01),
            SignalUtil.xor(SignalUtil.twoBytesFromInt(sender.getPort()),
                    Arrays.copyOf(msg.getHeader().getCookie(), 2)),
            SignalUtil.xor(sender.getAddress().getAddress(), msg.getHeader().getCookie()));

    StunAttribute attr = new StunAttribute(StunAttributeTypeEnum.XOR_MAPPED_ADDRESS, content);

    StunAttribute user = msg.getAttributeSet().get(StunAttributeTypeEnum.USERNAME);
    String strUser = new String(user.toBytes()).split(":")[0].trim();

    msg.validate(password, data);/*w w  w . j  a va 2 s.c om*/

    HashMap<StunAttributeTypeEnum, StunAttribute> outSet = new HashMap<>();
    outSet.put(StunAttributeTypeEnum.XOR_MAPPED_ADDRESS, attr);
    outSet.putAll(msg.getAttributeSet());

    StunMessage output = StunMessage.fromData(StunRequestTypeEnum.BINDING_RESPONSE, msg.getHeader().getCookie(),
            msg.getHeader().getTransactionID(), outSet, true, true, strUser, password);

    byte[] bt = output.toBytes();
    logger.trace("Response: " + Hex.encodeHexString(bt));
    return bt;
}

From source file:org.olat.core.util.httpclient.EasySSLSocketFactory.java

@Override
public Socket connectSocket(int connectTimeout, Socket sock, HttpHost host, InetSocketAddress remoteAddress,
        InetSocketAddress localAddress, HttpContext context) throws IOException {

    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

    int localPort = 0;
    if (localAddress != null) {
        // we need to bind explicitly
        if (localAddress.getPort() < 0) {
            localPort = 0; // indicates "any"
        }/*from w ww . ja  v a2s .c o m*/
        InetSocketAddress isa = new InetSocketAddress(localAddress.getAddress(), localPort);
        sslsock.bind(isa);
    }

    sslsock.connect(remoteAddress, 10000);
    sslsock.setSoTimeout(10000);
    return sslsock;
}

From source file:backup.namenode.NameNodeBackupServicePlugin.java

@Override
public void start(Object service) {
    UserGroupInformation ugi;//from w  w w. j  av  a  2 s .c o m
    try {
        ugi = UserGroupInformation.getCurrentUser();
        LOG.info("Starting NameNodeBackupServicePlugin with ugi {}", ugi);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Configuration conf = getConf();
    NameNode namenode = (NameNode) service;
    BlockManager blockManager = namenode.getNamesystem().getBlockManager();
    // This object is created here so that it's lifecycle follows the namenode
    try {
        restoreProcessor = SingletonManager.getManager(NameNodeRestoreProcessor.class).getInstance(namenode,
                () -> new NameNodeRestoreProcessor(getConf(), namenode, ugi));
        LOG.info("NameNode Backup plugin setup using UGI {}", ugi);

        NameNodeBackupRPCImpl backupRPCImpl = new NameNodeBackupRPCImpl(blockManager);

        InetSocketAddress listenerAddress = namenode.getServiceRpcAddress();
        int ipcPort = listenerAddress.getPort();
        String bindAddress = listenerAddress.getAddress().getHostAddress();
        int port = conf.getInt(DFS_BACKUP_NAMENODE_RPC_PORT_KEY, DFS_BACKUP_NAMENODE_RPC_PORT_DEFAULT);
        if (port == 0) {
            port = ipcPort + 1;
        }
        server = new RPC.Builder(conf).setBindAddress(bindAddress).setPort(port).setInstance(backupRPCImpl)
                .setProtocol(NameNodeBackupRPC.class).build();
        ServiceAuthorizationManager serviceAuthorizationManager = server.getServiceAuthorizationManager();
        serviceAuthorizationManager.refresh(conf, new BackupPolicyProvider());
        server.start();

        LOG.info("NameNode Backup RPC listening on {}", port);

        int httpPort = getConf().getInt(DFS_BACKUP_NAMENODE_HTTP_PORT_KEY,
                DFS_BACKUP_NAMENODE_HTTP_PORT_DEFAULT);
        if (httpPort != 0) {
            ClassLoader classLoader = getClassLoader();
            if (classLoader != null) {
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                try {
                    BackupWebService<Stats> stats = getBackupWebService(ugi, blockManager, restoreProcessor);

                    // Have to setup classloader in thread context to get the static
                    // files in the http server tp be setup correctly.
                    Thread.currentThread().setContextClassLoader(classLoader);
                    Class<?> backupStatusServerClass = classLoader.loadClass(BACKUP_WEB_BACKUP_WEB_SERVER);

                    Object server = DuckTypeUtil.newInstance(backupStatusServerClass,
                            new Class[] { Integer.TYPE, BackupWebService.class },
                            new Object[] { httpPort, stats });
                    httpServer = DuckTypeUtil.wrap(HttpServer.class, server);
                    httpServer.start();
                    LOG.info("NameNode Backup HTTP listening on {}", httpPort);
                } finally {
                    Thread.currentThread().setContextClassLoader(contextClassLoader);
                }
            } else {
                LOG.info("NameNode Backup HTTP classes not found.");
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:tajo.worker.Worker.java

private void prepareServing() throws IOException {
    defaultFS = FileSystem.get(URI.create(conf.getVar(ConfVars.ENGINE_BASE_DIR)), conf);

    localFS = FileSystem.getLocal(conf);
    Path workDirPath = new Path(workDir.toURI());
    if (!localFS.exists(workDirPath)) {
        localFS.mkdirs(workDirPath);//from w  w  w  . ja  va  2s.c o  m
        LOG.info("local temporal dir is created: " + localFS.exists(workDirPath));
        LOG.info("local temporal dir (" + workDir + ") is created");
    }

    String hostname = DNS.getDefaultHost(conf.get("nta.master.dns.interface", "default"),
            conf.get("nta.master.dns.nameserver", "default"));
    int port = this.conf.getIntVar(ConfVars.LEAFSERVER_PORT);

    // Creation of a HSA will force a resolve.
    InetSocketAddress initialIsa = new InetSocketAddress(hostname, port);
    if (initialIsa.getAddress() == null) {
        throw new IllegalArgumentException("Failed resolve of " + this.isa);
    }
    this.rpcServer = NettyRpc.getProtoParamRpcServer(this, AsyncWorkerProtocol.class, initialIsa);
    this.rpcServer.start();

    // Set our address.
    this.isa = this.rpcServer.getBindAddress();
    this.serverName = this.isa.getHostName() + ":" + this.isa.getPort();

    this.zkClient = new ZkClient(this.conf);
    this.queryLauncher = new QueryLauncher();
    this.queryLauncher.start();
    this.queryEngine = new TQueryEngine(conf);

    this.retriever = new AdvancedDataRetriever();
    this.dataServer = new HttpDataServer(NetUtils.createSocketAddr(hostname, 0), retriever);
    this.dataServer.start();

    InetSocketAddress dataServerAddr = this.dataServer.getBindAddress();
    this.dataServerURL = "http://" + dataServerAddr.getAddress().getHostAddress() + ":"
            + dataServerAddr.getPort();
    LOG.info("dataserver listens on " + dataServerURL);

    this.workerContext = new WorkerContext();
    Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook()));
}

From source file:com.all.networking.AbstractNetworkingService.java

@Override
public final void messageReceived(IoSession session, Object message) {
    String json = null;//w  w  w  .  j  a v  a2  s. c o  m
    try {
        byte[] decodedBytes = Base64.decode(message.toString().getBytes());
        CharBuffer charBuff = UTF_DECODER.decode(ByteBuffer.wrap(decodedBytes));
        json = charBuff.toString();
    } catch (Exception e) {
        LOG.warn("Could not decode message with UTF-8.");
        json = new String(Base64.decode(message.toString().getBytes()));
    }
    NetworkingMessage networkingMessage = JsonConverter.toBean(json, NetworkingMessage.class);
    if (networkingMessage.isSplit()) {
        networkingMessage = mergeNetworkingMessageChunk(networkingMessage);
    }
    if (networkingMessage != null) {
        AllMessage<?> actualMessage = networkingMessage.getBody();
        InetSocketAddress remoteAddress = (InetSocketAddress) session.getRemoteAddress();
        actualMessage.putProperty(MESSAGE_SENDER_PUBLIC_ADDRESS, remoteAddress.getAddress().getHostAddress());
        actualMessage.putProperty(MESSAGE_SENDER, networkingMessage.getSender());
        actualMessage.putProperty(NETWORKING_SESSION_ID, Long.toString(session.getId()));
        sessionUpdated(session, networkingMessage);
        onAllMessage(actualMessage);
    }
}