Example usage for java.net InetSocketAddress toString

List of usage examples for java.net InetSocketAddress toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Constructs a string representation of this InetSocketAddress.

Usage

From source file:com.evilisn.DAO.CertMapper.java

public static byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception

{

    InputStream is = null;/*from w  ww  . ja va 2  s.c  o  m*/

    InputStream is_temp = null;

    try {

        if (uri == null)
            return null;

        URL url = uri.toURL();

        if (bActiveCheckUnknownHost) {

            url.getProtocol();

            String host = url.getHost();

            int port = url.getPort();

            if (port == -1)

                port = url.getDefaultPort();

            InetSocketAddress isa = new InetSocketAddress(host, port);

            if (isa.isUnresolved()) {

                //fix JNLP popup error issue

                throw new UnknownHostException("Host Unknown:" + isa.toString());

            }

        }

        HttpURLConnection uc = (HttpURLConnection) url.openConnection();

        uc.setDoInput(true);

        uc.setAllowUserInteraction(false);

        uc.setInstanceFollowRedirects(true);

        setTimeout(uc);

        String contentEncoding = uc.getContentEncoding();

        int len = uc.getContentLength();

        // is = uc.getInputStream();

        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1)

        {

            is_temp = uc.getInputStream();

            is = new GZIPInputStream(is_temp);

        }

        else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1)

        {

            is_temp = uc.getInputStream();

            is = new InflaterInputStream(is_temp);

        }

        else

        {

            is = uc.getInputStream();

        }

        if (len != -1) {

            int ch = 0, i = 0;

            byte[] res = new byte[len];

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

            }

            return res;

        } else {

            ArrayList<byte[]> buffer = new ArrayList<byte[]>();

            int buf_len = 1024;

            byte[] res = new byte[buf_len];

            int ch = 0, i = 0;

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

                if (i == buf_len) {

                    //rotate

                    buffer.add(res);

                    i = 0;

                    res = new byte[buf_len];

                }

            }

            int total_len = buffer.size() * buf_len + i;

            byte[] buf = new byte[total_len];

            for (int j = 0; j < buffer.size(); j++) {

                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }

            if (i > 0) {

                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }

            return buf;

        }

    } catch (Exception e) {

        e.printStackTrace();

        return null;

    } finally {

        closeInputStream(is_temp);

        closeInputStream(is);

    }

}

From source file:edu.umass.cs.nio.MessageExtractor.java

/**
 * For comparing json-smart with org.json.
 * /*from   w  w w .j a va2  s  . com*/
 * @param sndrAddress
 * @param rcvrAddress
 * @param json
 * @return Parsed JSON object.
 */
public static net.minidev.json.JSONObject stampAddressIntoJSONObject(InetSocketAddress sndrAddress,
        InetSocketAddress rcvrAddress, net.minidev.json.JSONObject json) {
    // only put the IP field in if it doesn't exist already
    try {
        // put sender address
        if (!json.containsKey(MessageNIOTransport.SNDR_ADDRESS_FIELD))
            json.put(MessageNIOTransport.SNDR_ADDRESS_FIELD, sndrAddress.toString());

        // put receiver socket address
        if (!json.containsKey(MessageNIOTransport.RCVR_ADDRESS_FIELD))
            json.put(MessageNIOTransport.RCVR_ADDRESS_FIELD, rcvrAddress.toString());

    } catch (Exception e) {
        log.severe("Encountered JSONException while stamping sender address and port at receiver: ");
        e.printStackTrace();
    }
    return json;
}

From source file:org.apache.hadoop.hdfs.BlockReaderTestUtil.java

/**
 * Get a BlockReader for the given block.
 *//*from w w w  .j a v a2 s  . c  om*/
public static BlockReader getBlockReader(MiniDFSCluster cluster, LocatedBlock testBlock, int offset,
        int lenToRead) throws IOException {
    InetSocketAddress targetAddr = null;
    ExtendedBlock block = testBlock.getBlock();
    DatanodeInfo[] nodes = testBlock.getLocations();
    targetAddr = NetUtils.createSocketAddr(nodes[0].getXferAddr());

    final DistributedFileSystem fs = cluster.getFileSystem();
    return new BlockReaderFactory(fs.getClient().getConf()).setInetSocketAddress(targetAddr)
            .setExtendedBlock(block).setFileName(targetAddr.toString() + ":" + block.getBlockId())
            .setBlockToken(testBlock.getBlockToken()).setStartOffset(offset).setLength(lenToRead)
            .setVerifyChecksum(true).setClientName("BlockReaderTestUtil").setDatanodeInfo(nodes[0])
            .setClientCacheContext(ClientContext.getFromConf(fs.getConf()))
            .setCachingStrategy(CachingStrategy.newDefaultStrategy()).setConfiguration(fs.getConf())
            .setAllowShortCircuitLocalReads(true).setTracer(FsTracer.get(fs.getConf()))
            .setRemotePeerFactory(new RemotePeerFactory() {
                @Override
                public SocketFactory getSocketFactory(Configuration conf) throws IOException {
                    return NetUtils.getDefaultSocketFactory(conf);
                }

                @Override
                public Peer newConnectedPeer(InetSocketAddress addr, Token<BlockTokenIdentifier> blockToken,
                        DatanodeID datanodeId) throws IOException {
                    Peer peer = null;
                    Socket sock = getSocketFactory(fs.getConf()).createSocket();
                    try {
                        sock.connect(addr, HdfsServerConstants.READ_TIMEOUT);
                        sock.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);
                        peer = TcpPeerServer.peerFromSocket(sock);
                    } finally {
                        if (peer == null) {
                            IOUtils.closeQuietly(sock);
                        }
                    }
                    return peer;
                }
            }).build();
}

From source file:BlockReaderFactory.java

/**
 * File name to print when accessing a block directly (from servlets)
 * @param s Address of the block location
 * @param poolId Block pool ID of the block
 * @param blockId Block ID of the block//w w w.  ja  va  2  s  .  co m
 * @return string that has a file name for debug purposes
 */
public static String getFileName(final InetSocketAddress s, final String poolId, final long blockId) {
    return s.toString() + ":" + poolId + ":" + blockId;
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestAccessTokenWithDFS.java

private static void tryRead(Configuration conf, LocatedBlock lblock, boolean shouldSucceed) {
    InetSocketAddress targetAddr = null;
    Socket s = null;/*  w w w .j  a  v  a  2s  . c o  m*/
    BlockReader blockReader = null;
    Block block = lblock.getBlock();
    try {
        DatanodeInfo[] nodes = lblock.getLocations();
        targetAddr = NetUtils.createSocketAddr(nodes[0].getName());
        s = new Socket();
        s.connect(targetAddr, HdfsConstants.READ_TIMEOUT);
        s.setSoTimeout(HdfsConstants.READ_TIMEOUT);

        blockReader = BlockReader.newBlockReader(s, targetAddr.toString() + ":" + block.getBlockId(),
                block.getBlockId(), lblock.getAccessToken(), block.getGenerationStamp(), 0, -1,
                conf.getInt("io.file.buffer.size", 4096));

    } catch (IOException ex) {
        if (ex instanceof InvalidAccessTokenException) {
            assertFalse("OP_READ_BLOCK: access token is invalid, " + "when it is expected to be valid",
                    shouldSucceed);
            return;
        }
        fail("OP_READ_BLOCK failed due to reasons other than access token");
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (IOException iex) {
            } finally {
                s = null;
            }
        }
    }
    if (blockReader == null) {
        fail("OP_READ_BLOCK failed due to reasons other than access token");
    }
    assertTrue("OP_READ_BLOCK: access token is valid, " + "when it is expected to be invalid", shouldSucceed);
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestBlockTokenWithDFS.java

private static void tryRead(Configuration conf, LocatedBlock lblock, boolean shouldSucceed) {
    InetSocketAddress targetAddr = null;
    Socket s = null;//w ww.  j av a  2  s  .  co  m
    DFSClient.BlockReader blockReader = null;
    Block block = lblock.getBlock();
    try {
        DatanodeInfo[] nodes = lblock.getLocations();
        targetAddr = NetUtils.createSocketAddr(nodes[0].getName());
        s = new Socket();
        s.connect(targetAddr, HdfsConstants.READ_TIMEOUT);
        s.setSoTimeout(HdfsConstants.READ_TIMEOUT);

        blockReader = DFSClient.BlockReader.newBlockReader(s, targetAddr.toString() + ":" + block.getBlockId(),
                block.getBlockId(), lblock.getBlockToken(), block.getGenerationStamp(), 0, -1,
                conf.getInt("io.file.buffer.size", 4096));

    } catch (IOException ex) {
        if (ex instanceof InvalidBlockTokenException) {
            assertFalse("OP_READ_BLOCK: access token is invalid, " + "when it is expected to be valid",
                    shouldSucceed);
            return;
        }
        fail("OP_READ_BLOCK failed due to reasons other than access token");
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (IOException iex) {
            } finally {
                s = null;
            }
        }
    }
    if (blockReader == null) {
        fail("OP_READ_BLOCK failed due to reasons other than access token");
    }
    assertTrue("OP_READ_BLOCK: access token is valid, " + "when it is expected to be invalid", shouldSucceed);
}

From source file:ch.epfl.eagle.daemon.nodemonitor.ConfigNodeMonitorState.java

@Override
public boolean registerBackend(String appId, InetSocketAddress nodeMonitor) {
    // Verify that the given backend information matches the static configuration.
    if (!appId.equals(staticAppId)) {
        LOG.error("Requested to register backend for app " + appId + " but was expecting app " + staticAppId);
    } else if (!nodeMonitors.contains(nodeMonitor)) {
        StringBuilder errorMessage = new StringBuilder();
        for (InetSocketAddress nodeMonitorAddress : nodeMonitors) {
            errorMessage.append(nodeMonitorAddress.toString());
        }/*w  w w. j  a v  a 2 s.com*/
        throw new RuntimeException(
                "Address " + nodeMonitor.toString() + " not found among statically configured addreses for app "
                        + appId + " (statically " + "configured addresses include: " + errorMessage.toString());
    }

    return true;
}

From source file:alluxio.cli.fs.command.MasterInfoCommand.java

@Override
public int run(CommandLine cl) {
    MasterInquireClient inquireClient = MasterInquireClient.Factory.create();
    try {//  ww  w  .  j  ava 2 s. c o m
        InetSocketAddress leaderAddress = inquireClient.getPrimaryRpcAddress();
        System.out.println("Current leader master: " + leaderAddress.toString());
    } catch (UnavailableException e) {
        System.out.println("Failed to find leader master");
    }

    try {
        List<InetSocketAddress> masterAddresses = inquireClient.getMasterRpcAddresses();
        System.out.println(String.format("All masters: %s", masterAddresses));
    } catch (UnavailableException e) {
        System.out.println("Failed to find all master addresses");
    }
    return 0;
}

From source file:cloudfoundry.norouter.f5.dropsonde.LoggingPoolPopulator.java

private boolean containsSelf(Optional<Collection<PoolMember>> poolMembers, InetSocketAddress poolMember) {
    return poolMembers.isPresent() && poolMembers.get().stream()
            .filter(member -> member.getName().equalsIgnoreCase(poolMember.toString())).findFirst().isPresent();
}

From source file:org.apache.niolex.config.service.impl.ReplicaServiceImpl.java

/**
 * Override super method/* w  w w  .  j a v a 2s. co  m*/
 * @see org.apache.niolex.config.service.ReplicaService#connectToOtherServers(java.net.InetSocketAddress[])
 */
@Override
public synchronized void connectToOtherServers(InetSocketAddress[] addresses) {
    for (InetSocketAddress addr : addresses) {
        if (!otherServers.containsKey(addr.toString())) {
            tryConnectToOtherServer(addr);
        }
    }
}