List of usage examples for javax.net SocketFactory createSocket
public Socket createSocket() throws IOException
From source file:com.cerema.cloud2.lib.common.network.AdvancedSslSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the * given time limit./*from w w w. ja va 2s . c om*/ * * @param host the host name/IP * @param port the port on the host * @param clientHost the local host name/IP to bind the socket to * @param clientPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined */ @Override public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { Log_OC.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":" + localPort + ", params: " + params); if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); //logSslInfo(); SocketFactory socketfactory = mSslContext.getSocketFactory(); Log_OC.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout()); Socket socket = socketfactory.createSocket(); enableSecureProtocols(socket); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.setSoTimeout(params.getSoTimeout()); socket.bind(localaddr); ServerNameIndicator.setServerNameIndication(host, (SSLSocket) socket); socket.connect(remoteaddr, timeout); verifyPeerIdentity(host, port, socket); return socket; }
From source file:com.zimbra.cs.mailclient.MailConnection.java
private Socket newSocket() throws IOException { SocketFactory sf = config.getSecurity() != MailConfig.Security.SSL ? getSocketFactory() : getSSLSocketFactory();//from w w w . ja v a 2s . c o m Socket sock = sf.createSocket(); int connectTimeout = (int) Math.min(config.getConnectTimeout() * 1000L, Integer.MAX_VALUE); int readTimeout = (int) Math.min(config.getReadTimeout() * 1000L, Integer.MAX_VALUE); sock.setSoTimeout(readTimeout > 0 ? readTimeout : Integer.MAX_VALUE); sock.connect(new InetSocketAddress(config.getHost(), config.getPort()), connectTimeout > 0 ? connectTimeout : Integer.MAX_VALUE); return sock; }
From source file:com.owncloud.android.authenticator.EasySSLSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the * given time limit.//from ww w .j av a 2 s . c o m * <p> * To circumvent the limitations of older JREs that do not support connect * timeout a controller thread is executed. The controller thread attempts * to create a new socket within the given limit of time. If socket * constructor does not return until the timeout expires, the controller * terminates and throws an {@link ConnectTimeoutException} * </p> * * @param host the host name/IP * @param port the port on the host * @param clientHost the local host name/IP to bind the socket to * @param clientPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { Log.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":" + localPort + ", params: " + params); if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); SocketFactory socketfactory = getSSLContext().getSocketFactory(); /*if (timeout == 0) { Log.d(TAG, " ... with connection timeout 0 and socket timeout " + params.getSoTimeout()); Socket socket = socketfactory.createSocket(host, port, localAddress, localPort); socket.setSoTimeout(params.getSoTimeout()); return socket; } else {*/ Log.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout()); Socket socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.setSoTimeout(params.getSoTimeout()); socket.bind(localaddr); socket.connect(remoteaddr, timeout); return socket; //} }
From source file:it.jnrpe.client.JNRPEClient.java
/** * Inovoke a command installed in JNRPE. * //w w w . j ava 2 s . c o m * @param sCommandName * The name of the command to be invoked * @param arguments * The arguments to pass to the command (will substitute the * $ARGSx$ parameters) * @return The value returned by the server * @throws JNRPEClientException * Thrown on any communication error. */ public final ReturnValue sendCommand(final String sCommandName, final String... arguments) throws JNRPEClientException { SocketFactory socketFactory; Socket s = null; try { if (!useSSL) { socketFactory = SocketFactory.getDefault(); } else { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, new TrustManager[] { getTrustManager() }, new SecureRandom()); socketFactory = sslContext.getSocketFactory(); } s = socketFactory.createSocket(); if (weakCipherSuitesEnabled) { SSLSocket ssl = (SSLSocket) s; ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites()); } s.setSoTimeout((int) TimeUnit.SECOND.convert(communicationTimeout)); s.connect(new InetSocketAddress(serverIPorURL, serverPort)); JNRPERequest req = new JNRPERequest(sCommandName, arguments); s.getOutputStream().write(req.toByteArray()); InputStream in = s.getInputStream(); JNRPEResponse res = new JNRPEResponse(in); return new ReturnValue(Status.fromIntValue(res.getResultCode()), res.getMessage()); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new JNRPEClientException(e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { // Ignore } } } }
From source file:com.appunite.websocket.WebSocket.java
/** * This method will be alive until error occur or interrupt was executed. * This method always throws some exception. (not thread safe) * // ww w.ja v a 2 s . co m * @param uri * uri of websocket * @throws UnknownHostException * when could not connect to selected host * @throws IOException * thrown when I/O exception occur * @throws WrongWebsocketResponse * thrown when wrong web socket response received * @throws InterruptedException * thrown when interrupt method was invoked */ public void connect(Uri uri) throws IOException, WrongWebsocketResponse, InterruptedException { checkNotNull(uri, "Uri cannot be null"); try { synchronized (mLockObj) { checkState(State.DISCONNECTED.equals(mState), "connect could be called only if disconnected"); SocketFactory factory; if (isSsl(uri)) { factory = SSLSocketFactory.getDefault(); } else { factory = SocketFactory.getDefault(); } mSocket = factory.createSocket(); mState = State.CONNECTING; mLockObj.notifyAll(); } mSocket.connect(new InetSocketAddress(uri.getHost(), getPort(uri))); mInputStream = new WebSocketReader(mSocket.getInputStream()); mOutputStream = new WebSocketWriter(mSocket.getOutputStream()); String secret = generateHandshakeSecret(); writeHeaders(uri, secret); readHandshakeHeaders(secret); } catch (IOException e) { synchronized (mLockObj) { if (State.DISCONNECTING.equals(mState)) { throw new InterruptedException(); } else { throw e; } } } finally { synchronized (mLockObj) { mState = State.DISCONNECTED; mLockObj.notifyAll(); } } try { synchronized (mLockObj) { mState = State.CONNECTED; mLockObj.notifyAll(); } mListener.onConnected(); //noinspection InfiniteLoopStatement for (;;) { doRead(); } } catch (NotConnectedException e) { synchronized (mLockObj) { if (State.DISCONNECTING.equals(mState)) { throw new InterruptedException(); } else { throw new RuntimeException(); } } } catch (IOException e) { synchronized (mLockObj) { if (State.DISCONNECTING.equals(mState)) { throw new InterruptedException(); } else { throw e; } } } finally { synchronized (mLockObj) { while (mWriting != 0) { mLockObj.wait(); } mState = State.DISCONNECTED; mLockObj.notifyAll(); } } }
From source file:org.apache.hadoop.hdfs.DataStreamer.java
/** * Create a socket for a write pipeline//w w w .ja v a 2 s .co m * * @param first the first datanode * @param length the pipeline length * @param client client * @return the socket connected to the first datanode */ static Socket createSocketForPipeline(final DatanodeInfo first, final int length, final DFSClient client) throws IOException { final String dnAddr = first.getXferAddr(client.getConf().connectToDnViaHostname); if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Connecting to datanode " + dnAddr); } final InetSocketAddress isa = NetUtils.createSocketAddr(dnAddr); SocketFactory socketFactory = new StandardSocketFactory(); final Socket sock = socketFactory.createSocket(); final int timeout = client.getDatanodeReadTimeout(length); NetUtils.connect(sock, isa, client.getRandomLocalInterfaceAddr(), client.getConf().socketTimeout); sock.setSoTimeout(timeout); sock.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE); if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Send buf size " + sock.getSendBufferSize()); } return sock; }
From source file:org.apache.geode.internal.net.SocketCreator.java
/** * Return a client socket, timing out if unable to connect and timeout > 0 (millis). The parameter * <i>timeout</i> is ignored if SSL is being used, as there is no timeout argument in the ssl * socket factory/*from www .j av a 2 s. co m*/ */ public Socket connect(InetAddress inetadd, int port, int timeout, ConnectionWatcher optionalWatcher, boolean clientSide, int socketBufferSize, boolean sslConnection) throws IOException { Socket socket = null; SocketAddress sockaddr = new InetSocketAddress(inetadd, port); printConfig(); try { if (sslConnection) { if (this.sslContext == null) { throw new GemFireConfigException("SSL not configured correctly, Please look at previous error"); } SocketFactory sf = this.sslContext.getSocketFactory(); socket = sf.createSocket(); // Optionally enable SO_KEEPALIVE in the OS network protocol. socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE); // If necessary, set the receive buffer size before connecting the // socket so that large buffers will be allocated on accepted sockets // (see java.net.Socket.setReceiverBufferSize javadocs for details) if (socketBufferSize != -1) { socket.setReceiveBufferSize(socketBufferSize); } if (optionalWatcher != null) { optionalWatcher.beforeConnect(socket); } socket.connect(sockaddr, Math.max(timeout, 0)); configureClientSSLSocket(socket, timeout); return socket; } else { if (clientSide && this.clientSocketFactory != null) { socket = this.clientSocketFactory.createSocket(inetadd, port); } else { socket = new Socket(); // Optionally enable SO_KEEPALIVE in the OS network protocol. socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE); // If necessary, set the receive buffer size before connecting the // socket so that large buffers will be allocated on accepted sockets // (see java.net.Socket.setReceiverBufferSize javadocs for details) if (socketBufferSize != -1) { socket.setReceiveBufferSize(socketBufferSize); } if (optionalWatcher != null) { optionalWatcher.beforeConnect(socket); } socket.connect(sockaddr, Math.max(timeout, 0)); } return socket; } } finally { if (optionalWatcher != null) { optionalWatcher.afterConnect(socket); } } }
From source file:org.apache.hadoop.hdfs.AvatarClient.java
/** * Get the checksum of a file.//from ww w. ja v a 2 s . com * @param src The file path * @return The checksum */ public static MD5MD5CRC32FileChecksum getFileChecksum(String src, AvatarProtocol namenode, SocketFactory socketFactory, int socketTimeout) throws IOException { //get all block locations final List<LocatedBlock> locatedblocks = callGetBlockLocations(namenode, src, 0, Long.MAX_VALUE) .getLocatedBlocks(); final DataOutputBuffer md5out = new DataOutputBuffer(); int bytesPerCRC = 0; long crcPerBlock = 0; //get block checksum for each block for (int i = 0; i < locatedblocks.size(); i++) { LocatedBlock lb = locatedblocks.get(i); final Block block = lb.getBlock(); final DatanodeInfo[] datanodes = lb.getLocations(); //try each datanode location of the block final int timeout = 3000 * datanodes.length + socketTimeout; boolean done = false; for (int j = 0; !done && j < datanodes.length; j++) { //connect to a datanode final Socket sock = socketFactory.createSocket(); NetUtils.connect(sock, NetUtils.createSocketAddr(datanodes[j].getName()), timeout); sock.setSoTimeout(timeout); DataOutputStream out = new DataOutputStream( new BufferedOutputStream(NetUtils.getOutputStream(sock), DataNode.SMALL_BUFFER_SIZE)); DataInputStream in = new DataInputStream(NetUtils.getInputStream(sock)); // get block MD5 try { if (LOG.isDebugEnabled()) { LOG.debug("write to " + datanodes[j].getName() + ": " + DataTransferProtocol.OP_BLOCK_CHECKSUM + ", block=" + block); } out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION); out.write(DataTransferProtocol.OP_BLOCK_CHECKSUM); out.writeLong(block.getBlockId()); out.writeLong(block.getGenerationStamp()); out.flush(); final short reply = in.readShort(); if (reply != DataTransferProtocol.OP_STATUS_SUCCESS) { throw new IOException("Bad response " + reply + " for block " + block + " from datanode " + datanodes[j].getName()); } //read byte-per-checksum final int bpc = in.readInt(); if (i == 0) { //first block bytesPerCRC = bpc; } else if (bpc != bytesPerCRC) { throw new IOException( "Byte-per-checksum not matched: bpc=" + bpc + " but bytesPerCRC=" + bytesPerCRC); } //read crc-per-block final long cpb = in.readLong(); if (locatedblocks.size() > 1 && i == 0) { crcPerBlock = cpb; } //read md5 final MD5Hash md5 = MD5Hash.read(in); md5.write(md5out); done = true; if (LOG.isDebugEnabled()) { if (i == 0) { LOG.debug("set bytesPerCRC=" + bytesPerCRC + ", crcPerBlock=" + crcPerBlock); } LOG.debug("got reply from " + datanodes[j].getName() + ": md5=" + md5); } } catch (IOException ie) { LOG.warn("src=" + src + ", datanodes[" + j + "].getName()=" + datanodes[j].getName(), ie); } finally { IOUtils.closeStream(in); IOUtils.closeStream(out); IOUtils.closeSocket(sock); } } if (!done) { throw new IOException("Fail to get block MD5 for " + block); } } //compute file MD5 final MD5Hash fileMD5 = MD5Hash.digest(md5out.getData()); return new MD5MD5CRC32FileChecksum(bytesPerCRC, crcPerBlock, fileMD5); }
From source file:org.apache.hadoop.hdfs.DFSClient.java
/** * Get the checksum of a file.//from w ww. j a va 2 s . c om * @param src The file path * @return The checksum */ public static MD5MD5CRC32FileChecksum getFileChecksum(String src, ClientProtocol namenode, SocketFactory socketFactory, int socketTimeout) throws IOException { //get all block locations LocatedBlocks blockLocations = callGetBlockLocations(namenode, src, 0, Long.MAX_VALUE); if (null == blockLocations) { throw new FileNotFoundException("File does not exist: " + src); } List<LocatedBlock> locatedblocks = blockLocations.getLocatedBlocks(); final DataOutputBuffer md5out = new DataOutputBuffer(); int bytesPerCRC = 0; long crcPerBlock = 0; boolean refetchBlocks = false; int lastRetriedIndex = -1; //get block checksum for each block for (int i = 0; i < locatedblocks.size(); i++) { if (refetchBlocks) { // refetch to get fresh tokens blockLocations = callGetBlockLocations(namenode, src, 0, Long.MAX_VALUE); if (null == blockLocations) { throw new FileNotFoundException("File does not exist: " + src); } locatedblocks = blockLocations.getLocatedBlocks(); refetchBlocks = false; } LocatedBlock lb = locatedblocks.get(i); final Block block = lb.getBlock(); final DatanodeInfo[] datanodes = lb.getLocations(); //try each datanode location of the block final int timeout = (socketTimeout > 0) ? (socketTimeout + HdfsConstants.READ_TIMEOUT_EXTENSION * datanodes.length) : 0; boolean done = false; for (int j = 0; !done && j < datanodes.length; j++) { Socket sock = null; DataOutputStream out = null; DataInputStream in = null; try { //connect to a datanode sock = socketFactory.createSocket(); NetUtils.connect(sock, NetUtils.createSocketAddr(datanodes[j].getName()), timeout); sock.setSoTimeout(timeout); out = new DataOutputStream( new BufferedOutputStream(NetUtils.getOutputStream(sock), DataNode.SMALL_BUFFER_SIZE)); in = new DataInputStream(NetUtils.getInputStream(sock)); if (LOG.isDebugEnabled()) { LOG.debug("write to " + datanodes[j].getName() + ": " + DataTransferProtocol.OP_BLOCK_CHECKSUM + ", block=" + block); } // get block MD5 out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION); out.write(DataTransferProtocol.OP_BLOCK_CHECKSUM); out.writeLong(block.getBlockId()); out.writeLong(block.getGenerationStamp()); lb.getBlockToken().write(out); out.flush(); final short reply = in.readShort(); if (reply != DataTransferProtocol.OP_STATUS_SUCCESS) { if (reply == DataTransferProtocol.OP_STATUS_ERROR_ACCESS_TOKEN && i > lastRetriedIndex) { if (LOG.isDebugEnabled()) { LOG.debug("Got access token error in response to OP_BLOCK_CHECKSUM " + "for file " + src + " for block " + block + " from datanode " + datanodes[j].getName() + ". Will retry the block once."); } lastRetriedIndex = i; done = true; // actually it's not done; but we'll retry i--; // repeat at i-th block refetchBlocks = true; break; } else { throw new IOException("Bad response " + reply + " for block " + block + " from datanode " + datanodes[j].getName()); } } //read byte-per-checksum final int bpc = in.readInt(); if (i == 0) { //first block bytesPerCRC = bpc; } else if (bpc != bytesPerCRC) { throw new IOException( "Byte-per-checksum not matched: bpc=" + bpc + " but bytesPerCRC=" + bytesPerCRC); } //read crc-per-block final long cpb = in.readLong(); if (locatedblocks.size() > 1 && i == 0) { crcPerBlock = cpb; } //read md5 final MD5Hash md5 = MD5Hash.read(in); md5.write(md5out); done = true; if (LOG.isDebugEnabled()) { if (i == 0) { LOG.debug("set bytesPerCRC=" + bytesPerCRC + ", crcPerBlock=" + crcPerBlock); } LOG.debug("got reply from " + datanodes[j].getName() + ": md5=" + md5); } } catch (IOException ie) { LOG.warn("src=" + src + ", datanodes[" + j + "].getName()=" + datanodes[j].getName(), ie); } finally { IOUtils.closeStream(in); IOUtils.closeStream(out); IOUtils.closeSocket(sock); } } if (!done) { throw new IOException("Fail to get block MD5 for " + block); } } //compute file MD5 final MD5Hash fileMD5 = MD5Hash.digest(md5out.getData()); return new MD5MD5CRC32FileChecksum(bytesPerCRC, crcPerBlock, fileMD5); }