Java Code Examples for java.net.InetSocketAddress

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project ardverk-commons, under directory /src/main/java/org/ardverk/net/.

Source file: NetworkUtils.java

  21 
vote

/** 
 * Resolves (if necessary) the given  {@link SocketAddress} and returns it.
 */
public static InetSocketAddress getResolved(SocketAddress address){
  InetSocketAddress isa=(InetSocketAddress)address;
  if (isa.isUnresolved()) {
    return new InetSocketAddress(isa.getHostName(),isa.getPort());
  }
  return isa;
}
 

Example 2

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/gameserver/.

Source file: SocketConnector.java

  20 
vote

SocketConnector(GameServer s){
  server=s;
  try {
    InetAddress address=InetAddress.getByName(GameOptions.host);
    InetSocketAddress bindAddr=new InetSocketAddress(address,GameOptions.port);
    socket=new ServerSocket();
    socket.bind(bindAddr);
    socket.setSoTimeout(1000);
  }
 catch (  IOException e) {
    System.err.println("Cannot resolve/bind to " + GameOptions.host + ":"+ GameOptions.port);
    e.printStackTrace();
  }
}
 

Example 3

From project big-data-plugin, under directory /shims/common/src/org/pentaho/hadoop/shim/common/.

Source file: CommonHadoopShim.java

  19 
vote

@Override public String[] getJobtrackerConnectionInfo(Configuration c){
  String[] result=new String[2];
  if (!"local".equals(c.get("mapred.job.tracker","local"))) {
    InetSocketAddress jobtracker=JobTracker.getAddress(ShimUtils.asConfiguration(c));
    result[0]=jobtracker.getHostName();
    result[1]=String.valueOf(jobtracker.getPort());
  }
  return result;
}
 

Example 4

From project cipango, under directory /cipango-server/src/main/java/org/cipango/server/nio/.

Source file: SelectChannelConnector.java

  19 
vote

@Override public void open() throws IOException {
synchronized (this) {
    if (_acceptChannel == null) {
      _acceptChannel=ServerSocketChannel.open();
      _acceptChannel.configureBlocking(true);
      _acceptChannel.socket().setReuseAddress(getReuseAddress());
      InetSocketAddress addr=new InetSocketAddress(InetAddress.getByName(getHost()),getPort());
      _acceptChannel.socket().bind(addr,getAcceptQueueSize());
      _localPort=_acceptChannel.socket().getLocalPort();
      if (_localPort <= 0)       throw new IOException("Server channel not bound");
    }
  }
}
 

Example 5

From project adbcj, under directory /postgresql/mina/src/main/java/org/adbcj/postgresql/mina/.

Source file: MinaConnectionManager.java

  18 
vote

public MinaConnectionManager(String host,int port,String username,String password,String database,Properties properties){
  super(username,password,database);
  logger.debug("Creating new Postgresql ConnectionManager");
  socketConnector=new NioSocketConnector();
  socketConnector.getSessionConfig().setTcpNoDelay(true);
  DefaultIoFilterChainBuilder filterChain=socketConnector.getFilterChain();
  filterChain.addLast(CODEC_NAME,new ProtocolCodecFilter(CODEC_FACTORY));
  socketConnector.setHandler(new IoHandler(this));
  InetSocketAddress address=new InetSocketAddress(host,port);
  socketConnector.setDefaultRemoteAddress(address);
}
 

Example 6

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/conn/scheme/.

Source file: SocketFactoryAdaptor.java

  18 
vote

public Socket connectSocket(final Socket socket,final String host,int port,final InetAddress localAddress,int localPort,final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  InetSocketAddress local=null;
  if (localAddress != null || localPort > 0) {
    if (localPort < 0) {
      localPort=0;
    }
    local=new InetSocketAddress(localAddress,localPort);
  }
  InetAddress remoteAddress=InetAddress.getByName(host);
  InetSocketAddress remote=new InetSocketAddress(remoteAddress,port);
  return this.factory.connectSocket(socket,remote,local,params);
}
 

Example 7

From project avro, under directory /lang/java/archetypes/avro-service-archetype/src/main/resources/archetype-resources/src/test/java/integration/.

Source file: SimpleOrderServiceIntegrationTest.java

  18 
vote

@BeforeClass public static void setupTransport() throws Exception {
  InetSocketAddress endpointAddress=new InetSocketAddress("0.0.0.0",12345);
  service=new SimpleOrderServiceEndpoint(endpointAddress);
  client=new SimpleOrderServiceClient(endpointAddress);
  service.start();
  client.start();
}
 

Example 8

From project capedwarf-green, under directory /connect/src/test/java/org/jboss/test/capedwarf/connect/support/.

Source file: SunHttpServerEmbedded.java

  18 
vote

public void start() throws IOException {
  if (server != null)   server.stop(0);
  InetSocketAddress isa=new InetSocketAddress("localhost",8080);
  server=HttpServer.create(isa,0);
  server.setExecutor(Executors.newCachedThreadPool());
  server.start();
}
 

Example 9

From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/channel/.

Source file: ChannelUtil.java

  18 
vote

/** 
 * Create a name for the channel based on the remote host's IP and port.
 */
static public String createChannelName(Channel channel){
  if (channel == null || channel.getRemoteAddress() == null) {
    return "ChannelWasNull";
  }
  if (channel.getRemoteAddress() instanceof InetSocketAddress) {
    InetSocketAddress addr=(InetSocketAddress)channel.getRemoteAddress();
    String remoteHostAddr=addr.getAddress().getHostAddress();
    int remoteHostPort=addr.getPort();
    return remoteHostAddr + ":" + remoteHostPort;
  }
 else {
    return channel.getRemoteAddress().toString();
  }
}
 

Example 10

From project curator, under directory /curator-test/src/main/java/com/netflix/curator/test/.

Source file: TestingCluster.java

  18 
vote

/** 
 * Given a ZooKeeper instance, returns which server it is connected to
 * @param client ZK instance
 * @return the server
 * @throws Exception errors
 */
public InstanceSpec findConnectionInstance(ZooKeeper client) throws Exception {
  Method m=client.getClass().getDeclaredMethod("testableRemoteSocketAddress");
  m.setAccessible(true);
  InetSocketAddress address=(InetSocketAddress)m.invoke(client);
  if (address != null) {
    for (    TestingZooKeeperServer server : servers) {
      if (server.getInstanceSpec().getPort() == address.getPort()) {
        return server.getInstanceSpec();
      }
    }
  }
  return null;
}
 

Example 11

From project Dempsy, under directory /lib-dempsyimpl/src/main/java/com/nokia/dempsy/messagetransport/tcp/.

Source file: TcpReceiver.java

  18 
vote

protected void bind() throws MessageTransportException {
  if (serverSocket == null || !serverSocket.isBound()) {
    try {
      InetSocketAddress inetSocketAddress=new InetSocketAddress(destination.inetAddress,destination.port < 0 ? 0 : destination.port);
      serverSocket=new ServerSocket();
      serverSocket.setReuseAddress(true);
      serverSocket.bind(inetSocketAddress);
      destination.port=serverSocket.getLocalPort();
    }
 catch (    IOException ioe) {
      throw new MessageTransportException("Cannot bind to port " + (destination.isEphemeral() ? "(ephemeral port)" : destination.port),ioe);
    }
  }
}
 

Example 12

From project DistCpV2-0.20.203, under directory /src/test/java/org/apache/hadoop/mapred/.

Source file: MockJobTracker.java

  18 
vote

public MockJobTracker(Configuration conf) throws IOException {
  localFileSystem=FileSystem.getLocal(new Configuration());
  InetSocketAddress addr=new InetSocketAddress("localhost",PORT);
  server=RPC.getServer(this,addr.getHostName(),addr.getPort(),1,false,conf,null);
  server.start();
}
 

Example 13

From project Agot-Java, under directory /src/main/java/got/client/.

Source file: Client.java

  17 
vote

public Client(){
  String host="127.0.0.1";
  int port=7890;
  ClientBootstrap bootstrap=new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));
  bootstrap.setPipelineFactory(new ChannelPipelineFactory(){
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new ObjectEncoder(),new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)),new ClientHandler(Client.this));
    }
  }
);
  ChannelFuture future=bootstrap.connect(new InetSocketAddress(host,port));
  future.getChannel().getCloseFuture().awaitUninterruptibly();
  bootstrap.releaseExternalResources();
}
 

Example 14

From project airlift, under directory /jmx/src/main/java/io/airlift/jmx/.

Source file: NetUtils.java

  17 
vote

public static int findUnusedPort() throws IOException {
  int port;
  ServerSocket socket=new ServerSocket();
  try {
    socket.bind(new InetSocketAddress(0));
    port=socket.getLocalPort();
  }
  finally {
    socket.close();
  }
  return port;
}
 

Example 15

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/net/.

Source file: ServerableConnectionManager.java

  17 
vote

protected void willStart(){
  super.willStart();
  try {
    ssocket=ServerSocketChannel.open();
    ssocket.configureBlocking(false);
    InetSocketAddress isa=null;
    if (ipAddress != null) {
      isa=new InetSocketAddress(ipAddress,port);
    }
 else {
      isa=new InetSocketAddress(port);
    }
    ssocket.socket().bind(isa);
    registerServerChannel(ssocket);
    Level level=log.getLevel();
    log.setLevel(Level.INFO);
    log.info("Server listening on " + isa + ".");
    log.setLevel(level);
  }
 catch (  IOException ioe) {
    log.error("Failure listening to socket on port '" + port + "'.",ioe);
    System.exit(-1);
  }
}
 

Example 16

From project android-bankdroid, under directory /src/eu/nullbyte/android/urllib/.

Source file: EasySSLSocketFactory.java

  17 
vote

/** 
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,java.lang.String,int,java.net.InetAddress,int,org.apache.http.params.HttpParams)
 */
public Socket connectSocket(Socket sock,String host,int port,InetAddress localAddress,int localPort,HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  int connTimeout=HttpConnectionParams.getConnectionTimeout(params);
  int soTimeout=HttpConnectionParams.getSoTimeout(params);
  InetSocketAddress remoteAddress=new InetSocketAddress(host,port);
  SSLSocket sslsock=(SSLSocket)((sock != null) ? sock : createSocket());
  if ((localAddress != null) || (localPort > 0)) {
    if (localPort < 0) {
      localPort=0;
    }
    InetSocketAddress isa=new InetSocketAddress(localAddress,localPort);
    sslsock.bind(isa);
  }
  sslsock.connect(remoteAddress,connTimeout);
  sslsock.setSoTimeout(soTimeout);
  return sslsock;
}
 

Example 17

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: SocketFactory.java

  17 
vote

public Socket createSocket(String name,int port,int timeout) throws IOException {
  if (factory != null) {
    return factory.createSocket(name,port,timeout);
  }
  Socket s=new Socket();
  s.connect(new InetSocketAddress(name,port),timeout);
  return s;
}
 

Example 18

From project apjp, under directory /APJP_LOCAL_JAVA/src/main/java/APJP/HTTP/.

Source file: HTTPProxyServer.java

  17 
vote

protected synchronized void startHTTPProxyServer() throws HTTPProxyServerException {
  logger.log(2,"HTTP_PROXY_SERVER/START_HTTP_PROXY_SERVER");
  try {
    serverSocket=new ServerSocket();
    serverSocket.bind(new InetSocketAddress(APJP.APJP_LOCAL_HTTP_PROXY_SERVER_ADDRESS,APJP.APJP_LOCAL_HTTP_PROXY_SERVER_PORT));
    thread=new Thread(this);
    thread.start();
  }
 catch (  Exception e) {
    logger.log(2,"HTTP_PROXY_SERVER/START_HTTP_PROXY_SERVER: EXCEPTION",e);
    throw new HTTPProxyServerException("HTTP_PROXY_SERVER/START_HTTP_PROXY_SERVER",e);
  }
}
 

Example 19

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/eventservice/.

Source file: ExternalPublisherEventService.java

  17 
vote

private InetSocketAddress getInetSocketAddress(String name) throws IOException {
  try {
    ServiceDescriptor sd=serviceLocator.selectServiceAtRandom(serviceSelector);
    int port=Integer.parseInt(sd.getProperties().get(name));
    String host=sd.getProperties().get(HOST);
    return new InetSocketAddress(host,port);
  }
 catch (  Exception e) {
    throw new IOException(e);
  }
}
 

Example 20

From project AutobahnAndroid, under directory /Autobahn/src/de/tavendo/autobahn/.

Source file: WebSocketConnection.java

  17 
vote

@Override protected String doInBackground(Void... params){
  Thread.currentThread().setName("WebSocketConnector");
  try {
    mTransportChannel=SocketChannel.open();
    mTransportChannel.socket().connect(new InetSocketAddress(mWsHost,mWsPort),mOptions.getSocketConnectTimeout());
    mTransportChannel.socket().setSoTimeout(mOptions.getSocketReceiveTimeout());
    mTransportChannel.socket().setTcpNoDelay(mOptions.getTcpNoDelay());
    return null;
  }
 catch (  IOException e) {
    return e.getMessage();
  }
}
 

Example 21

From project aws-tasks, under directory /src/main/java/datameer/awstasks/aws/ec2/support/.

Source file: Ec2SocketFactory.java

  17 
vote

@Override public Socket createSocket(String host,int port,InetAddress localHost,int localPort) throws IOException, UnknownHostException {
  Socket socket=createSocket();
  socket.bind(new InetSocketAddress(localHost,localPort));
  socket.connect(new InetSocketAddress(host,port));
  return socket;
}
 

Example 22

From project azure4j-blog-samples, under directory /Caching/MemcachedWebApp/src/com/persistent/memcached/client/.

Source file: MCacheClient.java

  17 
vote

/** 
 * Retrieves the Memcached client object.
 * @return memcached client object.
 * @throws IOException
 */
public static MemcachedClient getClient() throws IOException {
  if (memcachedClient == null) {
    LOGGER.info("#Creating new instance");
    boolean val=RoleEnvironment.isAvailable();
    if (val) {
      Collection<RoleInstance> roleInstances=RoleEnvironment.getRoles().get("WorkerRole1").getInstances().values();
      List<InetSocketAddress> addresses=new ArrayList<InetSocketAddress>();
      InetSocketAddress socketAddress=null;
      for (Iterator<RoleInstance> iterator=roleInstances.iterator(); iterator.hasNext(); ) {
        RoleInstance instance=iterator.next();
        socketAddress=instance.getInstanceEndpoints().get("Memcached.Endpoint").getIpEndPoint();
        LOGGER.info("#Host :: " + socketAddress.getHostString() + "#Port :: "+ socketAddress.getPort());
        addresses.add(socketAddress);
      }
      memcachedClient=new MemcachedClient(addresses);
    }
  }
  return memcachedClient;
}
 

Example 23

From project bbb-java, under directory /src/main/java/org/mconf/bbb/.

Source file: RtmpConnection.java

  17 
vote

public boolean connect(){
  if (factory == null)   factory=new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
  bootstrap=new ClientBootstrap(factory);
  bootstrap.setPipelineFactory(pipelineFactory());
  future=bootstrap.connect(new InetSocketAddress(options.getHost(),options.getPort()));
  future.addListener(this);
  return true;
}
 

Example 24

From project blacktie, under directory /stompconnect-1.0/src/main/java/org/codehaus/stomp/tcp/.

Source file: TcpTransport.java

  17 
vote

protected void connect() throws IOException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, URISyntaxException {
  if (socket == null && socketFactory == null) {
    throw new IllegalStateException("Cannot connect if the socket or socketFactory have not been set");
  }
  InetSocketAddress localAddress=null;
  InetSocketAddress remoteAddress=null;
  if (localLocation != null) {
    localAddress=new InetSocketAddress(InetAddress.getByName(localLocation.getHost()),localLocation.getPort());
  }
  if (remoteLocation != null) {
    String host=remoteLocation.getHost();
    remoteAddress=new InetSocketAddress(host,remoteLocation.getPort());
  }
  if (socket != null) {
    if (localAddress != null) {
      socket.bind(localAddress);
    }
    if (remoteAddress != null) {
      if (connectionTimeout >= 0) {
        socket.connect(remoteAddress,connectionTimeout);
      }
 else {
        socket.connect(remoteAddress);
      }
    }
  }
 else {
    if (localAddress != null) {
      socket=socketFactory.createSocket(remoteAddress.getAddress(),remoteAddress.getPort(),localAddress.getAddress(),localAddress.getPort());
    }
 else {
      socket=socketFactory.createSocket(remoteAddress.getAddress(),remoteAddress.getPort());
    }
  }
  this.dataIn=new DataInputStream(socket.getInputStream());
  this.dataOut=new DataOutputStream(socket.getOutputStream());
}
 

Example 25

From project c10n, under directory /core/src/test/java/c10n/resources/.

Source file: ExternalResourceTest.java

  17 
vote

private HttpServer serveTextOverHttp(final String text,String path,int port) throws IOException {
  HttpServer httpServer=HttpServer.create(new InetSocketAddress(port),0);
  HttpHandler handler=new HttpHandler(){
    @Override public void handle(    HttpExchange exchange) throws IOException {
      byte[] response=text.getBytes();
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK,response.length);
      exchange.getResponseBody().write(response);
      exchange.close();
    }
  }
;
  httpServer.createContext(path,handler);
  return httpServer;
}
 

Example 26

From project Cafe, under directory /webapp/src/org/openqa/selenium/net/.

Source file: PortProber.java

  17 
vote

private static int checkPortIsFree(int port){
  ServerSocket socket;
  try {
    socket=new ServerSocket();
    socket.setReuseAddress(true);
    socket.bind(new InetSocketAddress("localhost",port));
    int localPort=socket.getLocalPort();
    socket.close();
    return localPort;
  }
 catch (  IOException e) {
    return -1;
  }
}
 

Example 27

From project camel-websocket, under directory /src/main/java/org/apache/camel/component/websocket/.

Source file: WebsocketComponent.java

  17 
vote

protected Server createServer(ServletContextHandler context,String host,int port,String home){
  InetSocketAddress address=new InetSocketAddress(host,port);
  Server server=new Server(address);
  context.setContextPath("/");
  SessionManager sm=new HashSessionManager();
  SessionHandler sh=new SessionHandler(sm);
  context.setSessionHandler(sh);
  if (home != null) {
    context.setResourceBase(home);
    DefaultServlet defaultServlet=new DefaultServlet();
    ServletHolder holder=new ServletHolder(defaultServlet);
    holder.setInitParameter("useFileMappedBuffer","false");
    context.addServlet(holder,"/");
  }
  server.setHandler(context);
  return server;
}
 

Example 28

From project Cloud9, under directory /src/dist/edu/umd/hooka/.

Source file: PServer.java

  17 
vote

public PServer(int port,FileSystem fs,Path ttablePath) throws IOException {
  ttable=new TTable_monolithic_IFAs(fs,ttablePath,true);
  serverChannel=ServerSocketChannel.open();
  selector=Selector.open();
  serverChannel.socket().bind(new InetSocketAddress(port));
  serverChannel.configureBlocking(false);
  serverChannel.register(selector,SelectionKey.OP_ACCEPT);
  System.err.println("PServer initialized on " + InetAddress.getLocalHost() + ":"+ port);
}
 

Example 29

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/installer/.

Source file: AgentlessInstaller.java

  17 
vote

/** 
 * Checks if a TCP connection to a remote machine and port is possible.
 * @param ip remote machine ip.
 * @param port remote machine port.
 * @param timeout duration to wait for successful connection.
 * @param unit time unit to wait.
 * @throws InstallerException .
 * @throws InstallerException .
 * @throws TimeoutException .
 * @throws InterruptedException .
 * @throws ElasticMachineProvisioningException
 */
public static void checkConnection(final String ip,final int port,final long timeout,final TimeUnit unit) throws TimeoutException, InterruptedException, InstallerException {
  final long end=System.currentTimeMillis() + unit.toMillis(timeout);
  final InetAddress inetAddress=waitForRoute(ip,Math.min(end,System.currentTimeMillis() + DEFAULT_ROUTE_RESOLUTION_TIMEOUT));
  final InetSocketAddress socketAddress=new InetSocketAddress(inetAddress,port);
  logger.fine("Checking connection to: " + socketAddress);
  while (System.currentTimeMillis() + CONNECTION_TEST_SLEEP_BEFORE_RETRY_MILLIS < end) {
    Thread.sleep(CONNECTION_TEST_SLEEP_BEFORE_RETRY_MILLIS);
    final Socket sock=new Socket();
    try {
      sock.connect(socketAddress,CONNECTION_TEST_SOCKET_CONNECT_TIMEOUT_MILLIS);
      return;
    }
 catch (    final IOException e) {
      logger.log(Level.FINE,"Checking connection to: " + socketAddress,e);
    }
 finally {
      if (sock != null) {
        try {
          sock.close();
        }
 catch (        final IOException e) {
          logger.fine("Failed to close socket");
        }
      }
    }
  }
  throw new TimeoutException("Failed connecting to " + ip + ":"+ port);
}
 

Example 30

From project cmsandroid, under directory /src/com/zia/freshdocs/net/.

Source file: EasySSLSocketFactory.java

  17 
vote

/** 
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,java.lang.String,int,java.net.InetAddress,int,org.apache.http.params.HttpParams)
 */
public Socket connectSocket(Socket sock,String host,int port,InetAddress localAddress,int localPort,HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  int connTimeout=HttpConnectionParams.getConnectionTimeout(params);
  int soTimeout=HttpConnectionParams.getSoTimeout(params);
  InetSocketAddress remoteAddress=new InetSocketAddress(host,port);
  SSLSocket sslsock=(SSLSocket)((sock != null) ? sock : createSocket());
  if ((localAddress != null) || (localPort > 0)) {
    if (localPort < 0) {
      localPort=0;
    }
    InetSocketAddress isa=new InetSocketAddress(localAddress,localPort);
    sslsock.bind(isa);
  }
  sslsock.connect(remoteAddress,connTimeout);
  sslsock.setSoTimeout(soTimeout);
  return sslsock;
}
 

Example 31

From project cometd, under directory /cometd-java/cometd-java-oort/src/main/java/org/cometd/oort/.

Source file: OortMulticastConfigurer.java

  17 
vote

public void start() throws Exception {
  MulticastSocket sender=new MulticastSocket();
  sender.setTimeToLive(timeToLive);
  InetSocketAddress bindSocketAddress=bindAddress == null ? new InetSocketAddress(groupPort) : new InetSocketAddress(bindAddress,groupPort);
  MulticastSocket receiver=new MulticastSocket(bindSocketAddress);
  if (groupAddress == null)   groupAddress=InetAddress.getByName("239.255.0.1");
  receiver.joinGroup(groupAddress);
  active=true;
  senderThread=new Thread(new MulticastSender(sender),"Oort Multicast Sender");
  senderThread.setDaemon(true);
  senderThread.start();
  receiverThread=new Thread(new MulticastReceiver(receiver),"Oort Multicast Receiver");
  receiverThread.setDaemon(true);
  receiverThread.start();
}
 

Example 32

From project CommitCoin, under directory /src/com/google/bitcoin/core/.

Source file: TCPNetworkConnection.java

  17 
vote

public void connect(PeerAddress peerAddress,int connectTimeoutMsec) throws IOException, ProtocolException {
  remoteIp=peerAddress.getAddr();
  int port=(peerAddress.getPort() > 0) ? peerAddress.getPort() : this.params.port;
  InetSocketAddress address=new InetSocketAddress(remoteIp,port);
  socket.connect(address,connectTimeoutMsec);
  out=socket.getOutputStream();
  in=socket.getInputStream();
  log.info("Announcing ourselves as: {}",myVersionMessage.subVer);
  writeMessage(myVersionMessage);
  Message m=readMessage();
  if (!(m instanceof VersionMessage)) {
    throw new ProtocolException("First message received was not a version message but rather " + m);
  }
  versionMessage=(VersionMessage)m;
  writeMessage(new VersionAck());
  readMessage();
  int peerVersion=versionMessage.clientVersion;
  log.info("Connected to peer: version={}, subVer='{}', services=0x{}, time={}, blocks={}",new Object[]{peerVersion,versionMessage.subVer,versionMessage.localServices,new Date(versionMessage.time * 1000),versionMessage.bestHeight});
  if (!versionMessage.hasBlockChain()) {
    try {
      shutdown();
    }
 catch (    IOException ex) {
    }
    throw new ProtocolException("Peer does not have a copy of the block chain.");
  }
  serializer.setUseChecksumming(peerVersion >= 209);
}
 

Example 33

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/.

Source file: NetUtil.java

  17 
vote

/** 
 * Parses a comma-separated string of <code>&lt;host&gt;:&lt;port&gt;</code> pairs into a  {@link Collection} of{@link InetSocketAddress} values. If any particular host/port pair is a host only, the default port value is used.
 * @param hostPortPairs the comma-separated list of host/port pairs
 * @param defaultPort the port to use if not specified in <code>hostPortPairs</code>
 */
public static Collection<InetSocketAddress> hostPortPairsFromString(final String hostPortPairs,final int defaultPort){
  final Collection<InetSocketAddress> rv=new LinkedList<InetSocketAddress>();
  if (hostPortPairs != null && hostPortPairs.trim().length() > 0) {
    for (    final String pair : hostPortPairs.split(",")) {
      final String[] parts=pair.split(":");
      if (parts.length > 0) {
        final String host=parts[0].trim();
        final int port=parts.length > 1 ? Integer.parseInt(parts[1]) : defaultPort;
        rv.add(new InetSocketAddress(host,port));
      }
    }
  }
  return rv;
}
 

Example 34

From project components-ness-httpserver_1, under directory /src/test/java/com/nesscomputing/httpserver/.

Source file: TestGuiceModule.java

  17 
vote

private static int findUnusedPort() throws IOException {
  int port;
  ServerSocket socket=new ServerSocket();
  try {
    socket.bind(new InetSocketAddress(0));
    port=socket.getLocalPort();
  }
  finally {
    socket.close();
  }
  return port;
}
 

Example 35

From project components-ness-jmx, under directory /src/main/java/com/nesscomputing/jmx/starter/.

Source file: NetUtils.java

  17 
vote

public static int findUnusedPort() throws IOException {
  int port;
  final ServerSocket socket=new ServerSocket();
  try {
    socket.bind(new InetSocketAddress(0));
    port=socket.getLocalPort();
  }
  finally {
    socket.close();
  }
  return port;
}
 

Example 36

From project Countandra, under directory /src/org/countandra/netty/.

Source file: NettyUtils.java

  17 
vote

public static synchronized void startupNettyServer(int httpPort){
  if (nettyStarted)   return;
  nettyStarted=true;
  ServerBootstrap server=new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));
  server.setPipelineFactory(new CountandraHttpServerPipelineFactory());
  server.bind(new InetSocketAddress(httpPort));
}
 

Example 37

From project crash, under directory /shell/core/src/main/java/org/crsh/util/.

Source file: AbstractSocketClient.java

  17 
vote

public final void connect() throws IOException {
  Socket socket=new Socket();
  socket.connect(new InetSocketAddress(port));
  InputStream in=socket.getInputStream();
  OutputStream out=socket.getOutputStream();
  this.socket=socket;
  this.in=in;
  this.out=out;
  handle(in,out);
}
 

Example 38

From project daap, under directory /src/main/java/org/ardverk/daap/.

Source file: DaapConfig.java

  17 
vote

public DaapConfig(){
  name=DEFAULT_SERVER_NAME;
  address=new InetSocketAddress(DEFAULT_PORT);
  backlog=DEFAULT_BACKLOG;
  maxConnections=DEFAULT_MAX_CONNECTIONS;
  bufferSize=DEFAULT_BUFFER_SIZE;
  authenticationMethod=NO_PASSWORD;
  authenticationScheme=BASIC_SCHEME;
}
 

Example 39

From project datasalt-utils, under directory /src/contrib/java/org/apache/solr/cloud/.

Source file: SolrZkServer.java

  17 
vote

public Long getMySeverId(){
  if (zkRun == null && solrPort == null)   return null;
  Map<Long,QuorumPeer.QuorumServer> slist=getServers();
  String myHost="localhost";
  InetSocketAddress thisAddr=null;
  if (zkRun != null && zkRun.length() > 0) {
    String parts[]=zkRun.split(":");
    myHost=parts[0];
    thisAddr=new InetSocketAddress(myHost,Integer.parseInt(parts[1]) + 1);
  }
 else {
    thisAddr=new InetSocketAddress(myHost,Integer.parseInt(solrPort) + 1001);
  }
  Long me=null;
  boolean multiple=false;
  int port=0;
  for (  QuorumPeer.QuorumServer server : slist.values()) {
    if (server.addr.getHostName().equals(myHost)) {
      multiple=me != null;
      me=server.id;
      port=server.addr.getPort();
    }
  }
  if (!multiple) {
    setClientPort(port - 1);
    return me;
  }
  if (me == null) {
    return null;
  }
  for (  QuorumPeer.QuorumServer server : slist.values()) {
    if (server.addr.equals(thisAddr)) {
      if (clientPortAddress == null || clientPortAddress.getPort() <= 0)       setClientPort(server.addr.getPort() - 1);
      return server.id;
    }
  }
  return null;
}
 

Example 40

From project distributed_loadgen, under directory /src/com/couchbase/loadgen/memcached/.

Source file: SpymemcachedClient.java

  17 
vote

/** 
 * Initialize any state for this DB. Called once per DB instance; there is one DB instance per client thread.
 */
public void init(){
  int membaseport=((Integer)Config.getConfig().get(Config.MEMCACHED_PORT)).intValue();
  String addr=(String)Config.getConfig().get(Config.MEMCACHED_ADDRESS);
  String protocol=(String)Config.getConfig().get(Config.PROTOCOL);
  try {
    InetSocketAddress ia=new InetSocketAddress(InetAddress.getByAddress(ipv4AddressToByte(addr)),membaseport);
    if (protocol.equals(PROTO_BINARY)) {
      client=new MemcachedClient(new BinaryConnectionFactory(),Arrays.asList(ia));
    }
 else     if (protocol.equals(PROTO_ASCII)) {
      client=new MemcachedClient(ia);
    }
 else {
      LOG.info("ERROR: BAD PROTOCOL");
      ClusterManager.getManager().finishedLoadGeneration();
    }
  }
 catch (  UnknownHostException e) {
    e.printStackTrace();
  }
catch (  IOException e1) {
    e1.printStackTrace();
  }
}
 

Example 41

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/message/.

Source file: AclsClient.java

  16 
vote

public Response serverSendReceive(Request r) throws AclsException {
  try {
    Socket aclsSocket=new Socket();
    try {
      aclsSocket.setSoTimeout(timeout);
      aclsSocket.connect(new InetSocketAddress(serverHost,serverPort),timeout);
      BufferedWriter w=new BufferedWriter(new OutputStreamWriter(aclsSocket.getOutputStream()));
      InputStream is=aclsSocket.getInputStream();
      LOG.debug("Sending ACLS server request " + r.getType().name() + "("+ r.unparse(true)+ ")");
      w.append(r.unparse(false) + "\r\n").flush();
      return new ResponseReaderImpl().readWithStatusLine(is);
    }
  finally {
      aclsSocket.close();
    }
  }
 catch (  SocketTimeoutException ex) {
    LOG.info("ACLS send / receive timed out");
    throw new AclsNoResponseException("Timeout while connecting or talking to ACLS server (" + serverHost + ":"+ serverPort+ ")",ex);
  }
catch (  IOException ex) {
    LOG.info("ACLS send / receive gave IO exception: " + ex.getMessage());
    throw new AclsCommsException("IO error while trying to talk to ACLS server (" + serverHost + ":"+ serverPort+ ")",ex);
  }
}
 

Example 42

From project android-rackspacecloud, under directory /extensions/httpnio/src/main/java/org/jclouds/http/httpnio/pool/.

Source file: NioHttpCommandConnectionPool.java

  16 
vote

@Inject public NioHttpCommandConnectionPool(ExecutorService executor,Semaphore allConnections,BlockingQueue<HttpCommandRendezvous<?>> commandQueue,BlockingQueue<NHttpConnection> available,AsyncNHttpClientHandler clientHandler,DefaultConnectingIOReactor ioReactor,HttpParams params,URI endPoint,@Named(Constants.PROPERTY_MAX_CONNECTION_REUSE) int maxConnectionReuse,@Named(Constants.PROPERTY_MAX_SESSION_FAILURES) int maxSessionFailures){
  super(executor,allConnections,commandQueue,available,endPoint,maxConnectionReuse,maxSessionFailures);
  String host=checkNotNull(checkNotNull(endPoint,"endPoint").getHost(),String.format("Host null for endpoint %s",endPoint));
  int port=endPoint.getPort();
  if (endPoint.getScheme().equals("https")) {
    try {
      this.dispatch=provideSSLClientEventDispatch(clientHandler,params);
    }
 catch (    KeyManagementException e) {
      throw new RuntimeException("SSL error creating a connection to " + endPoint,e);
    }
catch (    NoSuchAlgorithmException e) {
      throw new RuntimeException("SSL error creating a connection to " + endPoint,e);
    }
    if (port == -1)     port=443;
  }
 else {
    this.dispatch=provideClientEventDispatch(clientHandler,params);
    if (port == -1)     port=80;
  }
  checkArgument(port > 0,String.format("Port %d not in range for endpoint %s",endPoint.getPort(),endPoint));
  this.ioReactor=ioReactor;
  this.sessionCallback=new NHttpClientConnectionPoolSessionRequestCallback();
  this.target=new InetSocketAddress(host,port);
  clientHandler.setEventListener(this);
}
 

Example 43

From project android_8, under directory /src/com/defuzeme/network/.

Source file: Connector.java

  16 
vote

private boolean connectSocket(StreamAuthObject object){
  Network._socketAddress=new InetSocketAddress(object.ip,object.port);
  try {
    Network._socket=SocketFactory.getDefault().createSocket();
    Network._socket.connect(Network._socketAddress,Settings._TimeOut);
    Network._socket.setSoTimeout(Settings._TimeOut);
    Network._input=new InputStreamReader(Network._socket.getInputStream());
    Network._output=new DataOutputStream(Network._socket.getOutputStream());
    return true;
  }
 catch (  IOException exception) {
    Log.w(this.getClass().getName(),exception.toString());
  }
  return false;
}
 

Example 44

From project ardverk-dht, under directory /components/core/src/test/java/org/ardverk/dht/codec/bencode/.

Source file: BencodeMessageCodecTest.java

  16 
vote

@Test public void encodeDecode() throws IOException {
  BencodeMessageCodec codec=new BencodeMessageCodec();
  MessageId messageId=MessageId.createRandom(20);
  KUID contactId=KUID.createRandom(20);
  Contact contact=new DefaultContact(Type.SOLICITED,contactId,0,false,new InetSocketAddress("localhost",6666));
  SocketAddress address=new InetSocketAddress("localhost",6666);
  PingRequest request=new DefaultPingRequest(messageId,contact,address);
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  Encoder encoder=codec.createEncoder(baos);
  encoder.write(request);
  encoder.close();
  ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
  Decoder decoder=codec.createDecoder(address,bais);
  Message message=decoder.read();
  decoder.close();
  TestCase.assertTrue(message instanceof PingRequest);
}
 

Example 45

From project asterisk-java, under directory /src/main/java/org/asteriskjava/util/internal/.

Source file: SocketConnectionFacadeImpl.java

  16 
vote

/** 
 * Creates a new instance for use with the Manager API that uses the given line delimiter.
 * @param host        the foreign host to connect to.
 * @param port        the foreign port to connect to.
 * @param ssl         <code>true</code> to use SSL, <code>false</code> otherwise.
 * @param timeout     0 incidcates default
 * @param readTimeout see {@link Socket#setSoTimeout(int)}
 * @param lineDelimiter a {@link Pattern} for matching the line delimiter for the socket
 * @throws IOException if the connection cannot be established.
 */
public SocketConnectionFacadeImpl(String host,int port,boolean ssl,int timeout,int readTimeout,Pattern lineDelimiter) throws IOException {
  Socket socket;
  if (ssl) {
    socket=SSLSocketFactory.getDefault().createSocket();
  }
 else {
    socket=SocketFactory.getDefault().createSocket();
  }
  socket.setSoTimeout(readTimeout);
  socket.connect(new InetSocketAddress(host,port),timeout);
  initialize(socket,lineDelimiter);
  if (System.getProperty(Trace.TRACE_PROPERTY,"false").equalsIgnoreCase("true")) {
    trace=new FileTrace(socket);
  }
}
 

Example 46

From project atlas, under directory /src/main/java/com/ning/atlas/.

Source file: SSH.java

  16 
vote

public void forwardLocalPortTo(int localPort,String targetHost,int targetPort) throws IOException {
  final LocalPortForwarder.Parameters params=new LocalPortForwarder.Parameters("localhost",localPort,targetHost,targetPort);
  final ServerSocket ss=new ServerSocket();
  ss.setReuseAddress(true);
  ss.bind(new InetSocketAddress(params.getLocalHost(),params.getLocalPort()));
  pool.submit(new Runnable(){
    @Override public void run(){
      try {
        ssh.newLocalPortForwarder(params,ss).listen();
      }
 catch (      IOException e) {
        logger.warn(e,"ioexception on local port forwarded");
      }
    }
  }
);
}
 

Example 47

From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/ea2/client/.

Source file: TaskClient.java

  16 
vote

public synchronized boolean connect(String target){
  disconnect();
  try {
    receiveSocket=new Socket();
    receiveSocket.setSoTimeout(5000);
    receiveSocket.connect(new InetSocketAddress(target,TaskServer.PORT));
    InputStream inStream=receiveSocket.getInputStream();
    Scanner inScanner=new Scanner(inStream);
    String line=inScanner.nextLine().trim();
    if ("None".equals(line)) {
      receiveSocket.close();
      receiveSocket=null;
      return false;
    }
    if (line.matches("^Lines\\s+[0-9]+$")) {
      int lineCount=Integer.parseInt(line.split("\\s+")[1]);
      String inLines="";
      for (int i=0; i < lineCount; i++) {
        inLines+=inScanner.nextLine().replaceAll("[\n\r]","") + "\n";
      }
      connectionParameters=new TaskParameters(inLines);
      socketOutStream=receiveSocket.getOutputStream();
      return true;
    }
    return false;
  }
 catch (  NoSuchElementException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  disconnect();
  return false;
}
 

Example 48

From project byteman, under directory /agent/src/main/java/org/jboss/byteman/agent/.

Source file: TransformListener.java

  16 
vote

public static synchronized boolean initialize(Retransformer retransformer,String hostname,Integer port){
  if (theTransformListener == null) {
    try {
      if (hostname == null) {
        hostname=DEFAULT_HOST;
      }
      if (port == null) {
        port=Integer.valueOf(DEFAULT_PORT);
      }
      theServerSocket=new ServerSocket();
      theServerSocket.bind(new InetSocketAddress(hostname,port.intValue()));
      if (Transformer.isVerbose()) {
        System.out.println("TransformListener() : accepting requests on " + hostname + ":"+ port);
      }
    }
 catch (    IOException e) {
      System.out.println("TransformListener() : unexpected exception opening server socket " + e);
      e.printStackTrace();
      return false;
    }
    theTransformListener=new TransformListener(retransformer);
    theTransformListener.start();
  }
  return true;
}
 

Example 49

From project caseconductor-platform, under directory /utest-domain-services/src/main/java/com/utest/domain/service/util/.

Source file: TrustedSSLUtil.java

  16 
vote

public Socket createSocket(final String host,final int port,final InetAddress localAddress,final int localPort,final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  if (params == null) {
    throw new IllegalArgumentException("Parameters may not be null");
  }
  final int timeout=params.getConnectionTimeout();
  final SocketFactory socketfactory=getSSLContext().getSocketFactory();
  if (timeout == 0) {
    return socketfactory.createSocket(host,port,localAddress,localPort);
  }
 else {
    final Socket socket=socketfactory.createSocket();
    final SocketAddress localaddr=new InetSocketAddress(localAddress,localPort);
    final SocketAddress remoteaddr=new InetSocketAddress(host,port);
    socket.bind(localaddr);
    socket.connect(remoteaddr,timeout);
    return socket;
  }
}
 

Example 50

From project chililog-server, under directory /src/main/java/org/chililog/server/pubsub/jsonhttp/.

Source file: JsonHttpService.java

  16 
vote

/** 
 * Start all pubsub services
 */
public synchronized void start(){
  _mqProducerSessionPool=new MqProducerSessionPool(AppProperties.getInstance().getPubSubJsonHttpNettyHandlerThreadPoolSize());
  AppProperties appProperties=AppProperties.getInstance();
  if (_channelFactory != null) {
    _logger.info("PubSub JSON HTTP Web Sever Already Started.");
    return;
  }
  _logger.info("Starting PubSub JSON HTTP  Web Sever on " + appProperties.getPubSubJsonHttpHost() + ":"+ appProperties.getPubSubJsonHttpPort()+ "...");
  int workerCount=appProperties.getPubSubJsonHttpNettyWorkerThreadPoolSize();
  if (workerCount == 0) {
    _channelFactory=new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
  }
 else {
    _channelFactory=new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool(),workerCount);
  }
  ServerBootstrap bootstrap=new ServerBootstrap(_channelFactory);
  Executor executor=Executors.newFixedThreadPool(appProperties.getPubSubJsonHttpNettyHandlerThreadPoolSize());
  bootstrap.setPipelineFactory(new JsonHttpServerPipelineFactory(executor));
  String[] hosts=TransportConfiguration.splitHosts(appProperties.getPubSubJsonHttpHost());
  for (  String h : hosts) {
    if (StringUtils.isBlank(h)) {
      if (hosts.length == 1) {
        h="0.0.0.0";
      }
 else {
        continue;
      }
    }
    SocketAddress address=h.equals("0.0.0.0") ? new InetSocketAddress(appProperties.getPubSubJsonHttpPort()) : new InetSocketAddress(h,appProperties.getPubSubJsonHttpPort());
    Channel channel=bootstrap.bind(address);
    _allChannels.add(channel);
  }
  _logger.info("PubSub JSON HTTP Web Sever Started.");
}
 

Example 51

From project CouchbaseMock, under directory /src/main/java/org/couchbase/mock/.

Source file: CouchbaseMock.java

  16 
vote

public void start(){
  nodeThreads=new ArrayList<Thread>();
  for (  String s : getBuckets().keySet()) {
    Bucket bucket=getBuckets().get(s);
    bucket.start(nodeThreads);
  }
  try {
    boolean busy=true;
    do {
      if (port == 0) {
        ServerSocket server=new ServerSocket(0);
        port=server.getLocalPort();
        server.close();
      }
      try {
        httpServer=HttpServer.create(new InetSocketAddress(port),10);
      }
 catch (      BindException ex) {
        System.err.println("Looks like port " + port + " busy, lets try another one");
      }
      busy=false;
    }
 while (busy);
    httpServer.createContext("/pools",new PoolsHandler(this)).setAuthenticator(authenticator);
    httpServer.setExecutor(Executors.newCachedThreadPool());
    httpServer.start();
    startupLatch.countDown();
  }
 catch (  IOException ex) {
    Logger.getLogger(CouchbaseMock.class.getName()).log(Level.SEVERE,null,ex);
    System.exit(-1);
  }
}
 

Example 52

From project Custom-Salem, under directory /src/haven/test/.

Source file: TestClient.java

  16 
vote

public TestClient(String user){
  try {
    addr=new InetSocketAddress(InetAddress.getByName("localhost"),1870);
  }
 catch (  java.net.UnknownHostException e) {
    throw (new RuntimeException("localhost not known"));
  }
  this.user=user;
  this.cookie=new byte[64];
  tg=new ThreadGroup(HackThread.tg(),"Test client"){
    public void uncaughtException(    Thread t,    Throwable e){
synchronized (errsync) {
        System.err.println("Exception in test client: " + TestClient.this.user);
        e.printStackTrace(System.err);
      }
      TestClient.this.stop();
    }
  }
;
}
 

Example 53

From project dmix, under directory /JMPDComm/src/org/a0z/mpd/.

Source file: MPDConnection.java

  16 
vote

final synchronized private int[] connect() throws MPDServerException, IOException {
  sock=new Socket();
  sock.connect(new InetSocketAddress(hostAddress,hostPort),CONNECTION_TIMEOUT);
  BufferedReader in=new BufferedReader(new InputStreamReader(sock.getInputStream()),1024);
  String line=in.readLine();
  if (line == null) {
    throw new MPDServerException("No response from server");
  }
 else   if (line.startsWith(MPD_RESPONSE_OK)) {
    String[] tmp=line.substring((MPD_RESPONSE_OK + " MPD ").length(),line.length()).split("\\.");
    int[] result=new int[tmp.length];
    for (int i=0; i < tmp.length; i++)     result[i]=Integer.parseInt(tmp[i]);
    return result;
  }
 else   if (line.startsWith(MPD_RESPONSE_ERR)) {
    throw new MPDServerException("Server error: " + line.substring(MPD_RESPONSE_ERR.length()));
  }
 else {
    throw new MPDServerException("Bogus response from server");
  }
}
 

Example 54

From project bagheera, under directory /src/main/java/com/mozilla/bagheera/http/.

Source file: SubmissionHandler.java

  15 
vote

private void handlePost(MessageEvent e,BagheeraHttpRequest request){
  HttpResponseStatus status=NOT_ACCEPTABLE;
  ChannelBuffer content=request.getContent();
  if (content.readable() && content.readableBytes() > 0) {
    BagheeraMessage.Builder bmsgBuilder=BagheeraMessage.newBuilder();
    bmsgBuilder.setNamespace(request.getNamespace());
    bmsgBuilder.setId(request.getId());
    bmsgBuilder.setIpAddr(ByteString.copyFrom(HttpUtil.getRemoteAddr(request,((InetSocketAddress)e.getChannel().getRemoteAddress()).getAddress())));
    bmsgBuilder.setPayload(ByteString.copyFrom(content.toByteBuffer()));
    bmsgBuilder.setTimestamp(System.currentTimeMillis());
    producer.send(bmsgBuilder.build());
    if (request.containsHeader("X-Obsolete-Document")) {
      String obsoleteId=request.getHeader("X-Obsolete-Document");
      BagheeraMessage.Builder obsBuilder=BagheeraMessage.newBuilder();
      obsBuilder.setOperation(Operation.DELETE);
      obsBuilder.setNamespace(request.getNamespace());
      obsBuilder.setId(obsoleteId);
      obsBuilder.setIpAddr(bmsgBuilder.getIpAddr());
      obsBuilder.setTimestamp(bmsgBuilder.getTimestamp());
      producer.send(obsBuilder.build());
    }
    status=CREATED;
  }
  updateRequestMetrics(request.getNamespace(),request.getMethod().getName(),content.readableBytes());
  writeResponse(status,e,request.getNamespace(),URI.create(request.getId()).toString());
}
 

Example 55

From project camel-zookeeper, under directory /src/test/java/org/apache/camel/component/zookeeper/.

Source file: ZooKeeperTestSupport.java

  15 
vote

public TestZookeeperServer(int clientPort,boolean clearServerData) throws Exception {
  if (clearServerData) {
    File working=new File("./target/zookeeper");
    deleteDir(working);
    if (working.exists()) {
      throw new Exception("Could not delete Test Zookeeper Server working dir ./target/zookeeper");
    }
  }
  zkServer=new ZooKeeperServer();
  File dataDir=new File("./target/zookeeper/log");
  File snapDir=new File("./target/zookeeper/data");
  FileTxnSnapLog ftxn=new FileTxnSnapLog(dataDir,snapDir);
  zkServer.setTxnLogFactory(ftxn);
  zkServer.setTickTime(1000);
  connectionFactory=new NIOServerCnxn.Factory(new InetSocketAddress("localhost",clientPort),0);
  connectionFactory.startup(zkServer);
}
 

Example 56

From project cas, under directory /cas-server-integration-memcached/src/main/java/org/jasig/cas/monitor/.

Source file: MemcachedMonitor.java

  15 
vote

/** 
 * Get cache statistics for all memcached hosts known to  {@link MemcachedClient}.
 * @return Statistics for all available hosts.
 */
protected CacheStatistics[] getStatistics(){
  long evictions;
  long size;
  long capacity;
  String name;
  Map<String,String> statsMap;
  final Map<SocketAddress,Map<String,String>> allStats=memcachedClient.getStats();
  final List<CacheStatistics> statsList=new ArrayList<CacheStatistics>();
  for (  final SocketAddress address : allStats.keySet()) {
    statsMap=allStats.get(address);
    if (statsMap.size() > 0) {
      size=Long.parseLong(statsMap.get("bytes"));
      capacity=Long.parseLong(statsMap.get("limit_maxbytes"));
      evictions=Long.parseLong(statsMap.get("evictions"));
      if (address instanceof InetSocketAddress) {
        name=((InetSocketAddress)address).getHostName();
      }
 else {
        name=address.toString();
      }
      statsList.add(new SimpleCacheStatistics(size,capacity,evictions,name));
    }
  }
  return statsList.toArray(new CacheStatistics[statsList.size()]);
}
 

Example 57

From project connectbot, under directory /src/com/trilead/ssh2/channel/.

Source file: LocalAcceptThread.java

  15 
vote

public LocalAcceptThread(ChannelManager cm,InetSocketAddress localAddress,String host_to_connect,int port_to_connect) throws IOException {
  this.cm=cm;
  this.host_to_connect=host_to_connect;
  this.port_to_connect=port_to_connect;
  ss=new ServerSocket();
  ss.bind(localAddress);
}
 

Example 58

From project Core_2, under directory /shell/src/main/java/org/jboss/forge/shell/util/.

Source file: ForgeProxySelector.java

  15 
vote

@Override public List<Proxy> select(URI uri){
  if (uri == null) {
    throw new IllegalArgumentException("URI can't be null.");
  }
  String protocol=uri.getScheme();
  if ("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol)) {
    ArrayList<Proxy> result=new ArrayList<Proxy>();
    result.add(new Proxy(Type.HTTP,new InetSocketAddress(proxySettings.getProxyHost(),proxySettings.getProxyPort())));
    if (proxySettings.isAuthenticationSupported()) {
      Authenticator.setDefault(new Authenticator(){
        protected PasswordAuthentication getPasswordAuthentication(){
          return new PasswordAuthentication(proxySettings.getProxyUserName(),proxySettings.getProxyPassword().toCharArray());
        }
      }
);
    }
    return result;
  }
  if (defaultProxySelector != null) {
    return defaultProxySelector.select(uri);
  }
 else {
    ArrayList<Proxy> result=new ArrayList<Proxy>();
    result.add(Proxy.NO_PROXY);
    return result;
  }
}
 

Example 59

From project dolphin, under directory /dolphinmaple/test/com/tan/udp/.

Source file: UDPClient.java

  15 
vote

/** 
 * @param args
 * @throws SocketException 
 */
public static void main(String[] args) throws Exception {
  System.out.println("------ Client ------");
  Scanner scanner=new Scanner(System.in);
  String content=scanner.next();
  byte[] buff=content.getBytes();
  DatagramPacket dp=new DatagramPacket(buff,0,buff.length,new InetSocketAddress("127.0.0.1",9999));
  DatagramSocket ds=new DatagramSocket();
  ds.send(dp);
  ds.close();
}
 

Example 60

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/child/.

Source file: ChildServiceDelegate.java

  15 
vote

public ChildServiceDelegate(Configuration conf,String jobId,InetSocketAddress amAddress){
  this.conf=conf;
  this.jobId=jobId;
  this.amAddress=amAddress;
  UserGroupInformation.setConfiguration(this.conf);
  this.rpc=YarnRPC.create(conf);
}