List of usage examples for java.net InetSocketAddress InetSocketAddress
private InetSocketAddress(int port, String hostname)
From source file:com.eu.remote.EasySSLSocketFactory.java
/** * * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket, java.lang.String, int, * java.net.InetAddress, int, * org.apache.http.params.HttpParams)//from w w w. ja v a 2s .co m */ @Override 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)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
From source file:com.bazaarvoice.dropwizard.caching.memcached.MemcachedResponseStoreFactory.java
/** * InetSocketAddress deserialization is broken in jackson 2.3.3, so using HostAndPort instead. * See: https://github.com/FasterXML/jackson-databind/issues/444 * Fix will be in 2.3.4, but not released yet (as of 2014-Jul-10). *//*w ww . j av a2 s . c o m*/ @JsonProperty void setServers(HostAndPort[] servers) { checkNotNull(servers); _servers = FluentIterable.from(Arrays.asList(servers)) .transform(new Function<HostAndPort, InetSocketAddress>() { public InetSocketAddress apply(HostAndPort input) { return new InetSocketAddress(input.getHostText(), input.getPort()); } }).toList(); }
From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java
/** * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called. * @param listener listener to notify of events * @throws IOException if socket error occurs * @throws NullPointerException if any argument is {@code null} *//* w ww.jav a 2 s . com*/ public void start(NatPmpEventListener listener) throws IOException { Validate.notNull(listener); MulticastSocket socket = null; try { final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD final int port = 5350; final InetSocketAddress groupAddress = new InetSocketAddress(group, port); socket = new MulticastSocket(port); if (!currentSocket.compareAndSet(null, socket)) { IOUtils.closeQuietly(socket); return; } socket.setReuseAddress(true); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface InetAddress addr = addrs.nextElement(); try { if (addr instanceof Inet4Address) { socket.joinGroup(groupAddress, networkInterface); } } catch (IOException ioe) { // NOPMD // occurs with certain interfaces // do nothing } } } ByteBuffer buffer = ByteBuffer.allocate(12); DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity()); while (true) { buffer.clear(); socket.receive(data); buffer.position(data.getLength()); buffer.flip(); if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore continue; } if (buffer.remaining() != 12) { // data isn't the expected size, ignore continue; } int version = buffer.get(0); if (version != 0) { // data doesn't have the correct version, ignore continue; } int opcode = buffer.get(1) & 0xFF; if (opcode != 128) { // data doesn't have the correct op, ignore continue; } int resultCode = buffer.getShort(2) & 0xFFFF; switch (resultCode) { case 0: break; default: continue; // data doesn't have a successful result, ignore } listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer)); } } catch (IOException ioe) { if (currentSocket.get() == null) { return; // ioexception caused by interruption/stop, so just return without propogating error up } throw ioe; } finally { IOUtils.closeQuietly(socket); currentSocket.set(null); } }
From source file:com.groupon.odo.tests.HttpUtils.java
public static String doProxyHttpsGet(String url, BasicNameValuePair[] data) throws Exception { String fullUrl = url;//from w w w. j ava 2s . c o m if (data != null) { if (data.length > 0) { fullUrl += "?"; } for (BasicNameValuePair bnvp : data) { fullUrl += bnvp.getName() + "=" + uriEncode(bnvp.getValue()) + "&"; } } TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } URL uri = new URL(fullUrl); int port = Utils.getSystemPort(Constants.SYS_FWD_PORT); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", port)); URLConnection connection = uri.openConnection(proxy); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String accumulator = ""; String line = ""; Boolean firstLine = true; while ((line = rd.readLine()) != null) { accumulator += line; if (!firstLine) { accumulator += "\n"; } else { firstLine = false; } } return accumulator; }
From source file:com.digitalpebble.stormcrawler.protocol.okhttp.HttpProtocol.java
@Override public void configure(Config conf) { super.configure(conf); this.maxContent = ConfUtils.getInt(conf, "http.content.limit", -1); int timeout = ConfUtils.getInt(conf, "http.timeout", 10000); this.completionTimeout = ConfUtils.getInt(conf, "topology.message.timeout.secs", completionTimeout); userAgent = getAgentString(conf);/*from w w w . j a v a 2 s. c om*/ okhttp3.OkHttpClient.Builder builder = new OkHttpClient.Builder().retryOnConnectionFailure(true) .followRedirects(false).connectTimeout(timeout, TimeUnit.MILLISECONDS) .writeTimeout(timeout, TimeUnit.MILLISECONDS).readTimeout(timeout, TimeUnit.MILLISECONDS); String proxyHost = ConfUtils.getString(conf, "http.proxy.host", null); int proxyPort = ConfUtils.getInt(conf, "http.proxy.port", 8080); boolean useProxy = proxyHost != null && proxyHost.length() > 0; // use a proxy? if (useProxy) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); builder.proxy(proxy); } client = builder.build(); }
From source file:com.alphabetbloc.accessmrs.utilities.MySSLSocketFactory.java
@Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (host == null) { throw new IllegalArgumentException("Target host may not be null."); }/*from ww w.j ava 2 s. c om*/ if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } if (App.DEBUG) Log.e(TAG + "delete", "ConnectSocket with " + "\n\t host=" + host + "\n\t port=" + port + "\n\t localport=" + localPort); 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); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); try { hostnameVerifier.verify(host, sslsock); } catch (IOException iox) { try { sslsock.close(); } catch (Exception x) { } throw iox; } return sslsock; }
From source file:com.pinterest.rocksplicator.controller.tasks.HealthCheckTask.java
@Override public void process(Context ctx) throws Exception { final String clusterName = ctx.getCluster(); try {/* w w w .j av a 2 s . c om*/ ClusterBean clusterBean = ZKUtil.getClusterConfig(zkClient, clusterName); if (clusterBean == null) { ctx.getTaskQueue().failTask(ctx.getId(), "Failed to read cluster config from zookeeper."); return; } Set<InetSocketAddress> hosts = new HashSet<>(); for (SegmentBean segmentBean : clusterBean.getSegments()) { for (HostBean hostBean : segmentBean.getHosts()) { hosts.add(new InetSocketAddress(hostBean.getIp(), hostBean.getPort())); } // check segment replica checkSegment(segmentBean, getParameter().getNumReplicas()); } // ping all hosts Set<String> badHosts = new HashSet<>(); for (InetSocketAddress hostAddr : hosts) { try { clientFactory.getClient(hostAddr).ping(); } catch (TException | ExecutionException ex) { // record bad host badHosts.add(hostAddr.toString()); } } if (!badHosts.isEmpty()) { ctx.getTaskQueue().failTask(ctx.getId(), String.format("Unable to ping hosts: %s", badHosts)); return; } LOG.info("All hosts are good"); ctx.getTaskQueue().finishTask(ctx.getId(), String.format("Cluster %s is healthy", clusterName)); } catch (Exception ex) { ctx.getTaskQueue().failTask(ctx.getId(), String.format("Cluster %s is unhealthy, reason = %s", clusterName, ex.getMessage())); } }
From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception { if (msg instanceof HttpRequest) { final HttpRequest httpRequest = (HttpRequest) msg; //Channel uaChannel = uaChannelCtx.channel(); // connect remote Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel())); final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel() .attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote(); // set local address if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) { bootstrap.localAddress(new InetSocketAddress( (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0)); }/* www . ja va 2 s. c om*/ bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future1) throws Exception { if (future1.isSuccess()) { if (apnProxyRemote.isAppleyRemoteRule()) { uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel())); future1.channel() .writeAndFlush(Unpooled.copiedBuffer( constructConnectRequestForProxy(httpRequest, apnProxyRemote), CharsetUtil.UTF_8)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { if (!future2.channel().config() .getOption(ChannelOption.AUTO_READ)) { future2.channel().read(); } } }); } else { HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established")); uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { // remove handlers uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline() .remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler( "UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel())); } }); } } else { if (uaChannelCtx.channel().isActive()) { uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); } ReferenceCountUtil.release(msg); }
From source file:com.amediamanager.springconfig.ServerConfig.java
@Bean @Scope(WebApplicationContext.SCOPE_APPLICATION) public MemcachedClient memcachedClient(final ConfigurationSettings settings) throws IOException { MemcachedClient client = null;//from www .j a v a 2 s. c om if (settings.getProperty(ConfigurationSettings.ConfigProps.CACHE_ENABLED).equalsIgnoreCase("true")) { String configEndpoint = settings.getProperty(ConfigurationSettings.ConfigProps.CACHE_ENDPOINT); Integer clusterPort = Integer .parseInt(settings.getProperty(ConfigurationSettings.ConfigProps.CACHE_PORT)); client = new MemcachedClient(new InetSocketAddress(configEndpoint, clusterPort)); } return client; }