List of usage examples for java.net Socket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:com.msopentech.thali.utilities.universal.HttpKeySocksProxyClientConnOperator.java
@Override public void openConnection(final OperatedClientConnection conn, final HttpHost target, final InetAddress local, final HttpContext context, final HttpParams params) throws IOException { Socket socket = null; Socket sslSocket = null;//www . ja va2s . c o m try { if (conn == null || target == null || params == null) { throw new IllegalArgumentException("Required argument may not be null"); } if (conn.isOpen()) { throw new IllegalStateException("Connection must not be open"); } // The original NetCipher code uses a SchemeSocketFactory class that isn't supported by the version // of Apache that ships standard with Android. It also doesn't support the layered socket factory // interface either. We work around this later on but for now we just get our HttpKeySSLSocketFactory Scheme scheme = schemeRegistry.getScheme(target.getSchemeName()); HttpKeySSLSocketFactory httpKeySSLSocketFactory = (HttpKeySSLSocketFactory) scheme.getSocketFactory(); int port = scheme.resolvePort(target.getPort()); String host = target.getHostName(); // Perform explicit SOCKS4a connection request. SOCKS4a supports remote host name resolution // (i.e., Tor resolves the hostname, which may be an onion address). // The Android (Apache Harmony) Socket class appears to support only SOCKS4 and throws an // exception on an address created using INetAddress.createUnresolved() -- so the typical // technique for using Java SOCKS4a/5 doesn't appear to work on Android: // https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/java/net/PlainSocketImpl.java // See also: http://www.mit.edu/~foley/TinFoil/src/tinfoil/TorLib.java, for a similar implementation // From http://en.wikipedia.org/wiki/SOCKS#SOCKS4a: // // field 1: SOCKS version number, 1 byte, must be 0x04 for this version // field 2: command code, 1 byte: // 0x01 = establish a TCP/IP stream connection // 0x02 = establish a TCP/IP port binding // field 3: network byte order port number, 2 bytes // field 4: deliberate invalid IP address, 4 bytes, first three must be 0x00 and the last one must not be 0x00 // field 5: the user ID string, variable length, terminated with a null (0x00) // field 6: the domain name of the host we want to contact, variable length, terminated with a null (0x00) socket = new Socket(); conn.opening(socket, target); socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS); socket.connect(proxy.address(), CONNECT_TIMEOUT_MILLISECONDS); DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream()); outputStream.write((byte) 0x04); outputStream.write((byte) 0x01); outputStream.writeShort((short) port); outputStream.writeInt(0x01); outputStream.write((byte) 0x00); outputStream.write(host.getBytes()); outputStream.write((byte) 0x00); DataInputStream inputStream = new DataInputStream(socket.getInputStream()); if (inputStream.readByte() != (byte) 0x00 || inputStream.readByte() != (byte) 0x5a) { throw new IOException("SOCKS4a connect failed"); } inputStream.readShort(); inputStream.readInt(); // In the NetCipher code we cast to SchemeLayeredSocketFactory and call createLayeredSocket which amongst // other things takes 'params' as an argument. But none of this is supported in Android. When I looked in // Java at what createLayeredSocket was actually doing it was just calling createSocket with exactly the // arguments used below (it ignored params completely). So we should be good. sslSocket = ((HttpKeySSLSocketFactory) httpKeySSLSocketFactory).createSocket(socket, host, port, true); conn.opening(sslSocket, target); sslSocket.setSoTimeout(READ_TIMEOUT_MILLISECONDS); prepareSocket(sslSocket, context, params); conn.openCompleted(httpKeySSLSocketFactory.isSecure(sslSocket), params); // TODO: clarify which connection throws java.net.SocketTimeoutException? } catch (IOException e) { try { if (sslSocket != null) { sslSocket.close(); } if (socket != null) { socket.close(); } } catch (IOException ioe) { } throw e; } }
From source file:MyZone.Settings.java
public boolean retrieveCert() { while (true) { try {/*from w ww . j av a2 s .c om*/ Socket toCAServer = new Socket(globalProperties.caAddress, globalProperties.caPort); toCAServer.setSoTimeout(IDLE_LIMIT); byte[] usernameBytes = username.getBytes("UTF-8"); DataOutputStream outToCAServer = new DataOutputStream(toCAServer.getOutputStream()); byte[] buffer = new byte[usernameBytes.length + 4]; int len = 0; System.arraycopy(intToByteArray(usernameBytes.length), 0, buffer, len, 4); len += 4; System.arraycopy(usernameBytes, 0, buffer, len, usernameBytes.length); outToCAServer.write(buffer, 0, buffer.length); outToCAServer.flush(); int i = 0; byte[] lenBytes = new byte[4]; while (i < 4) { i += toCAServer.getInputStream().read(lenBytes, i, 4 - i); if (i < 0) { if (DEBUG) { System.out.println("DEBUG: line 2529 of Settings.java"); } } try { Thread.sleep(100); } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } } } len = byteArrayToInt(lenBytes); byte[] certBytes = new byte[len]; i = 0; while (i < len) { i += toCAServer.getInputStream().read(certBytes, i, len - i); if (i < 0) { if (DEBUG) { System.out.println("DEBUG: line 2555 of Settings.java"); } len = 4; break; } try { Thread.sleep(100); } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } } } if (len == 4) { Thread.sleep(30000); outToCAServer.close(); toCAServer.close(); continue; } outToCAServer.close(); toCAServer.close(); globalProperties.caCertPath = prefix + "/CAs/"; CertVerifier y = new CertVerifier(); userCertificate uc = y.verifyCertificate(certBytes, globalProperties.caCertPath, globalProperties.keyPairAlgorithm, globalProperties.certSigAlgorithm); if (uc == null) { Thread.sleep(30000); continue; } File file = new File(prefix + username + "/cert/" + username + ".cert"); FileOutputStream fos = new FileOutputStream(file); fos.write(certBytes); fos.flush(); fos.close(); outToCAServer.close(); toCAServer.close(); return true; } catch (Exception e) { if (DEBUG) e.printStackTrace(); } } }
From source file:org.apache.nutch.protocol.ftp.Client.java
/** * open a passive data connection socket * //from w w w . java2 s .c o m * @param command * @param arg * @return * @throws IOException * @throws FtpExceptionCanNotHaveDataConnection */ protected Socket __openPassiveDataConnection(int command, String arg) throws IOException, FtpExceptionCanNotHaveDataConnection { Socket socket; // // 20040317, xing, accommodate ill-behaved servers, see below // int port_previous = __passivePort; if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) throw new FtpExceptionCanNotHaveDataConnection("pasv() failed. " + getReplyString()); try { __parsePassiveModeReply(getReplyStrings()[0]); } catch (MalformedServerReplyException e) { throw new FtpExceptionCanNotHaveDataConnection(e.getMessage()); } // // 20040317, xing, accommodate ill-behaved servers, see above // int count = 0; // System.err.println("__passivePort "+__passivePort); // System.err.println("port_previous "+port_previous); // while (__passivePort == port_previous) { // // just quit if too many tries. make it an exception here? // if (count++ > 10) // return null; // // slow down further for each new try // Thread.sleep(500*count); // if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) // throw new FtpExceptionCanNotHaveDataConnection( // "pasv() failed. " + getReplyString()); // //return null; // try { // __parsePassiveModeReply(getReplyStrings()[0]); // } catch (MalformedServerReplyException e) { // throw new FtpExceptionCanNotHaveDataConnection(e.getMessage()); // } // } socket = _socketFactory_.createSocket(__passiveHost, __passivePort); if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { socket.close(); return null; } if (__remoteVerificationEnabled && !verifyRemote(socket)) { InetAddress host1, host2; host1 = socket.getInetAddress(); host2 = getRemoteAddress(); socket.close(); // our precaution throw new FtpExceptionCanNotHaveDataConnection( "Host attempting data connection " + host1.getHostAddress() + " is not same as server " + host2.getHostAddress() + " So we intentionally close it for security precaution."); } if (__dataTimeout >= 0) socket.setSoTimeout(__dataTimeout); return socket; }
From source file:org.apache.hadoop.hdfs.DFSClient.java
/** * Get the checksum of a file.//from w w w . ja v a 2 s . com * @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); }
From source file:org.freedesktop.dbus.Transport.java
@SuppressWarnings("resource") public void connect(BusAddress address, int timeout) throws IOException { log.info("Connecting to " + address); OutputStream out = null;/*from w w w .j av a2s. co m*/ InputStream in = null; AFUNIXSocket us = null; Socket s = null; int mode = 0; int types = 0; if ("unix".equals(address.getType())) { types = SASL.AUTH_EXTERNAL; File sockFile = null; boolean abstractSock = false; if (null != address.getParameter("abstract")) { sockFile = new File(address.getParameter("abstract")); abstractSock = true; } else if (null != address.getParameter("path")) { sockFile = new File(address.getParameter("path")); } if (null != address.getParameter("listen")) { mode = SASL.MODE_SERVER; AFUNIXServerSocket uss = AFUNIXServerSocket.newInstance(); uss.bind(new AFUNIXSocketAddress(sockFile, abstractSock)); uss.setPassCred(true); s = uss.accept(); } else { mode = SASL.MODE_CLIENT; us = AFUNIXSocket.newInstance(); us.connect(new AFUNIXSocketAddress(sockFile, abstractSock)); us.setPassCred(true); s = us; } } else if ("tcp".equals(address.getType())) { types = SASL.AUTH_SHA; if (null != address.getParameter("listen")) { mode = SASL.MODE_SERVER; ServerSocket ss = new ServerSocket(); ss.bind(new InetSocketAddress(address.getParameter("host"), Integer.parseInt(address.getParameter("port")))); s = ss.accept(); } else { mode = SASL.MODE_CLIENT; s = new Socket(); s.connect(new InetSocketAddress(address.getParameter("host"), Integer.parseInt(address.getParameter("port")))); } } else { throw new IOException("unknown address type " + address.getType()); } in = s.getInputStream(); out = s.getOutputStream(); if (!(new SASL()).auth(mode, types, address.getParameter("guid"), out, in, us)) { out.close(); in.close(); s.close(); throw new IOException("Failed to auth"); } if (log.isTraceEnabled()) { log.trace("Setting timeout to " + timeout + " on Socket"); } s.setSoTimeout(timeout); this.mout = new MessageWriter(out); this.min = new MessageReader(in); log.info("Connection open"); }
From source file:org.apache.hadoop.hdfs.DFSClient.java
/** * Connect to the given datanode's datantrasfer port, and return * the resulting IOStreamPair. This includes encryption wrapping, etc. *//* w w w . ja va 2s. c o m*/ private IOStreamPair connectToDN(DatanodeInfo dn, int timeout, LocatedBlock lb) throws IOException { boolean success = false; Socket sock = null; try { sock = socketFactory.createSocket(); String dnAddr = dn.getXferAddr(getConf().isConnectToDnViaHostname()); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to datanode " + dnAddr); } NetUtils.connect(sock, NetUtils.createSocketAddr(dnAddr), timeout); sock.setSoTimeout(timeout); OutputStream unbufOut = NetUtils.getOutputStream(sock); InputStream unbufIn = NetUtils.getInputStream(sock); IOStreamPair ret = saslClient.newSocketSend(sock, unbufOut, unbufIn, this, lb.getBlockToken(), dn); success = true; return ret; } finally { if (!success) { IOUtils.closeSocket(sock); } } }
From source file:org.apache.hadoop.hdfs.server.datanode.DWRRDataXceiver.java
@Override public void writeBlock(final ExtendedBlock block, final Token<BlockTokenIdentifier> blockToken, final String clientname, final DatanodeInfo[] targets, final DatanodeInfo srcDataNode, final BlockConstructionStage stage, final int pipelineSize, final long minBytesRcvd, final long maxBytesRcvd, final long latestGenerationStamp, DataChecksum requestedChecksum, CachingStrategy cachingStrategy) throws IOException { previousOpClientName = clientname;/* w w w . ja v a2 s . c o m*/ updateCurrentThreadName("Receiving block " + block); isDatanode = clientname.length() == 0; isClient = !isDatanode; isTransfer = stage == BlockConstructionStage.TRANSFER_RBW || stage == BlockConstructionStage.TRANSFER_FINALIZED; this.stage = stage; this.block = block; this.latestGenerationStamp = latestGenerationStamp; this.minBytesRcvd = minBytesRcvd; // check single target for transfer-RBW/Finalized if (isTransfer && targets.length > 0) { throw new IOException(stage + " does not support multiple targets " + Arrays.asList(targets)); } if (LOG.isDebugEnabled()) { LOG.debug("opWriteBlock: stage=" + stage + ", clientname=" + clientname + "\n block =" + block + ", newGs=" + latestGenerationStamp + ", bytesRcvd=[" + minBytesRcvd + ", " + maxBytesRcvd + "]" + "\n targets=" + Arrays.asList(targets) + "; pipelineSize=" + pipelineSize + ", srcDataNode=" + srcDataNode); LOG.debug("isDatanode=" + isDatanode + ", isClient=" + isClient + ", isTransfer=" + isTransfer); LOG.debug("writeBlock receive buf size " + peer.getReceiveBufferSize() + " tcp no delay " + peer.getTcpNoDelay()); } // We later mutate block's generation stamp and length, but we need to // forward the original version of the block to downstream mirrors, so // make a copy here. final ExtendedBlock originalBlock = new ExtendedBlock(block); block.setNumBytes(DataXceiverServer.estimateBlockSize); LOG.info("Receiving " + block + " src: " + remoteAddress + " dest: " + localAddress); // reply to upstream datanode or client replyOut = new DataOutputStream( new BufferedOutputStream(getOutputStream(), HdfsConstants.SMALL_BUFFER_SIZE)); checkAccess(replyOut, isClient, block, blockToken, Op.WRITE_BLOCK, BlockTokenSecretManager.AccessMode.WRITE); mirrorOut = null; // stream to next target mirrorIn = null; // reply from next target Socket mirrorSock = null; // socket to next target blockReceiver = null; // responsible for data handling String mirrorNode = null; // the name:port of next target String firstBadLink = ""; // first datanode that failed in connection setup Status mirrorInStatus = SUCCESS; try { if (isDatanode || stage != BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) { // open a block receiver blockReceiver = new DWRRBlockReceiver(block, in, peer.getRemoteAddressString(), peer.getLocalAddressString(), stage, latestGenerationStamp, minBytesRcvd, maxBytesRcvd, clientname, srcDataNode, datanode, requestedChecksum, cachingStrategy); storageUuid = blockReceiver.getStorageUuid(); } else { storageUuid = datanode.data.recoverClose(block, latestGenerationStamp, minBytesRcvd); } // // Connect to downstream machine, if appropriate // if (targets.length > 0) { InetSocketAddress mirrorTarget = null; // Connect to backup machine mirrorNode = targets[0].getXferAddr(connectToDnViaHostname); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to datanode " + mirrorNode); } mirrorTarget = NetUtils.createSocketAddr(mirrorNode); mirrorSock = datanode.newSocket(); try { int timeoutValue = dnConf.socketTimeout + (HdfsServerConstants.READ_TIMEOUT_EXTENSION * targets.length); int writeTimeout = dnConf.socketWriteTimeout + (HdfsServerConstants.WRITE_TIMEOUT_EXTENSION * targets.length); NetUtils.connect(mirrorSock, mirrorTarget, timeoutValue); mirrorSock.setSoTimeout(timeoutValue); mirrorSock.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE); OutputStream unbufMirrorOut = NetUtils.getOutputStream(mirrorSock, writeTimeout); InputStream unbufMirrorIn = NetUtils.getInputStream(mirrorSock); if (dnConf.encryptDataTransfer && !dnConf.trustedChannelResolver.isTrusted(mirrorSock.getInetAddress())) { IOStreamPair encryptedStreams = DataTransferEncryptor.getEncryptedStreams(unbufMirrorOut, unbufMirrorIn, datanode.blockPoolTokenSecretManager .generateDataEncryptionKey(block.getBlockPoolId())); unbufMirrorOut = encryptedStreams.out; unbufMirrorIn = encryptedStreams.in; } mirrorOut = new DataOutputStream( new BufferedOutputStream(unbufMirrorOut, HdfsConstants.SMALL_BUFFER_SIZE)); mirrorIn = new DataInputStream(unbufMirrorIn); new Sender(mirrorOut).writeBlock(originalBlock, blockToken, clientname, targets, srcDataNode, stage, pipelineSize, minBytesRcvd, maxBytesRcvd, latestGenerationStamp, requestedChecksum, cachingStrategy); mirrorOut.flush(); // read connect ack (only for clients, not for replication req) if (isClient) { BlockOpResponseProto connectAck = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(mirrorIn)); mirrorInStatus = connectAck.getStatus(); firstBadLink = connectAck.getFirstBadLink(); if (LOG.isDebugEnabled() || mirrorInStatus != SUCCESS) { LOG.info("Datanode " + targets.length + " got response for connect ack " + " from downstream datanode with firstbadlink as " + firstBadLink); } } } catch (IOException e) { if (isClient) { BlockOpResponseProto.newBuilder().setStatus(ERROR) // NB: Unconditionally using the xfer addr w/o hostname .setFirstBadLink(targets[0].getXferAddr()).build().writeDelimitedTo(replyOut); replyOut.flush(); } IOUtils.closeStream(mirrorOut); mirrorOut = null; IOUtils.closeStream(mirrorIn); mirrorIn = null; IOUtils.closeSocket(mirrorSock); mirrorSock = null; if (isClient) { LOG.error(datanode + ":Exception transfering block " + block + " to mirror " + mirrorNode + ": " + e); throw e; } else { LOG.info(datanode + ":Exception transfering " + block + " to mirror " + mirrorNode + "- continuing without the mirror", e); } } } // send connect-ack to source for clients and not transfer-RBW/Finalized if (isClient && !isTransfer) { if (LOG.isDebugEnabled() || mirrorInStatus != SUCCESS) { LOG.info("Datanode " + targets.length + " forwarding connect ack to upstream firstbadlink is " + firstBadLink); } BlockOpResponseProto.newBuilder().setStatus(mirrorInStatus).setFirstBadLink(firstBadLink).build() .writeDelimitedTo(replyOut); replyOut.flush(); } // receive the block and mirror to the next target if (blockReceiver != null) { LOG.info("CAMAMILLA " + classId + " receive the block and mirror to the next target"); // TODO TODO log entra String mirrorAddr = (mirrorSock == null) ? null : mirrorNode; int len = blockReceiver.receiveBlock(mirrorOut, mirrorIn, replyOut, mirrorAddr, null, targets); DWRRRequestObject newReq = new DWRRRequestObject(this, classId, op, len); dwrrmanager.addOp(newReq, classId); LOG.info("CAMAMILLA " + classId + " encuada peticio WRITE "); // TODO TODO log } } catch (IOException ioe) { LOG.info("opWriteBlock " + block + " received exception " + ioe); throw ioe; } finally { // close all opened streams IOUtils.closeSocket(mirrorSock); } }
From source file:com.mirth.connect.connectors.tcp.TcpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage message) { TcpDispatcherProperties tcpDispatcherProperties = (TcpDispatcherProperties) connectorProperties; Status responseStatus = Status.QUEUED; String responseData = null;/*from w w w. j av a 2s.c o m*/ String responseStatusMessage = null; String responseError = null; boolean validateResponse = false; long dispatcherId = getDispatcherId(); String socketKey = dispatcherId + tcpDispatcherProperties.getRemoteAddress() + tcpDispatcherProperties.getRemotePort(); if (tcpDispatcherProperties.isOverrideLocalBinding()) { socketKey += tcpDispatcherProperties.getLocalAddress() + tcpDispatcherProperties.getLocalPort(); } Socket socket = null; Thread timeoutThread = null; try { // Do some validation first to avoid unnecessarily creating sockets if (StringUtils.isBlank(tcpDispatcherProperties.getRemoteAddress())) { throw new Exception("Remote address is blank."); } else if (NumberUtils.toInt(tcpDispatcherProperties.getRemotePort()) <= 0) { throw new Exception("Remote port is invalid."); } socket = connectedSockets.get(socketKey); timeoutThread = timeoutThreads.get(socketKey); // If keep connection open is true, then interrupt the thread so it won't close the socket if (tcpDispatcherProperties.isKeepConnectionOpen() && timeoutThread != null) { disposeThreadQuietly(socketKey); } // Initialize a new socket if our current one is invalid, the remote side has closed, or keep connection open is false if (!tcpDispatcherProperties.isKeepConnectionOpen() || socket == null || socket.isClosed() || (tcpDispatcherProperties.isCheckRemoteHost() && socket instanceof StateAwareSocketInterface && ((StateAwareSocketInterface) socket).remoteSideHasClosed())) { closeSocketQuietly(socketKey); logger.debug("Creating new socket (" + connectorProperties.getName() + " \"" + getDestinationName() + "\" on channel " + getChannelId() + ")."); String info = "Trying to connect on " + tcpDispatcherProperties.getRemoteAddress() + ":" + tcpDispatcherProperties.getRemotePort() + "..."; eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.CONNECTING, info)); if (tcpDispatcherProperties.isOverrideLocalBinding()) { socket = SocketUtil.createSocket(configuration, tcpDispatcherProperties.getLocalAddress(), NumberUtils.toInt(tcpDispatcherProperties.getLocalPort())); } else { socket = SocketUtil.createSocket(configuration); } ThreadUtils.checkInterruptedStatus(); connectedSockets.put(socketKey, socket); SocketUtil.connectSocket(socket, tcpDispatcherProperties.getRemoteAddress(), NumberUtils.toInt(tcpDispatcherProperties.getRemotePort()), responseTimeout); socket.setReuseAddress(true); socket.setReceiveBufferSize(bufferSize); socket.setSendBufferSize(bufferSize); socket.setSoTimeout(responseTimeout); socket.setKeepAlive(tcpDispatcherProperties.isKeepConnectionOpen()); eventController.dispatchEvent(new ConnectorCountEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.CONNECTED, SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket), true)); } ThreadUtils.checkInterruptedStatus(); // Send the message eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.SENDING, SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket))); BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), bufferSize); BatchStreamReader batchStreamReader = new DefaultBatchStreamReader(socket.getInputStream()); StreamHandler streamHandler = transmissionModeProvider.getStreamHandler(socket.getInputStream(), bos, batchStreamReader, tcpDispatcherProperties.getTransmissionModeProperties()); streamHandler.write(getTemplateBytes(tcpDispatcherProperties, message)); bos.flush(); if (!tcpDispatcherProperties.isIgnoreResponse()) { ThreadUtils.checkInterruptedStatus(); // Attempt to get the response from the remote endpoint try { String info = "Waiting for response from " + SocketUtil.getInetAddress(socket) + " (Timeout: " + tcpDispatcherProperties.getResponseTimeout() + " ms)... "; eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WAITING_FOR_RESPONSE, info)); byte[] responseBytes = streamHandler.read(); if (responseBytes != null) { responseData = new String(responseBytes, CharsetUtils.getEncoding(tcpDispatcherProperties.getCharsetEncoding())); responseStatusMessage = "Message successfully sent."; } else { responseStatusMessage = "Message successfully sent, but no response received."; } streamHandler.commit(true); responseStatus = Status.SENT; // We only want to validate the response if we were able to retrieve it successfully validateResponse = tcpDispatcherProperties.getDestinationConnectorProperties() .isValidateResponse(); } catch (IOException e) { // An exception occurred while retrieving the response if (e instanceof SocketTimeoutException || e.getCause() != null && e.getCause() instanceof SocketTimeoutException) { responseStatusMessage = "Timeout waiting for response"; if (!tcpDispatcherProperties.isQueueOnResponseTimeout()) { responseStatus = Status.ERROR; } } else { responseStatusMessage = "Error receiving response"; } responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseStatusMessage + ": " + e.getMessage(), e); logger.warn(responseStatusMessage + " (" + connectorProperties.getName() + " \"" + getDestinationName() + "\" on channel " + getChannelId() + ").", e); eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), message.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), responseStatusMessage + ".", e)); eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.FAILURE, responseStatusMessage + " from " + SocketUtil.getInetAddress(socket))); closeSocketQuietly(socketKey); } } else { try { // MIRTH-2980: Since we're ignoring responses, flush out the socket's input stream so it doesn't continually grow socket.getInputStream().skip(socket.getInputStream().available()); } catch (IOException e) { logger.warn("Error flushing socket input stream.", e); } // We're ignoring the response, so always return a successful response responseStatus = Status.SENT; responseStatusMessage = "Message successfully sent."; } if (tcpDispatcherProperties.isKeepConnectionOpen() && (getCurrentState() == DeployedState.STARTED || getCurrentState() == DeployedState.STARTING)) { if (sendTimeout > 0) { // Close the connection after the send timeout has been reached startThread(socketKey); } } else { // If keep connection open is false, then close the socket right now closeSocketQuietly(socketKey); } } catch (Throwable t) { disposeThreadQuietly(socketKey); closeSocketQuietly(socketKey); String monitorMessage = "Error sending message (" + SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket) + "): " + t.getMessage(); eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.FAILURE, monitorMessage)); // If an exception occurred then close the socket, even if keep connection open is true responseStatusMessage = t.getClass().getSimpleName() + ": " + t.getMessage(); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), t.getMessage(), t); String logMessage = "Error sending message via TCP (" + connectorProperties.getName() + " \"" + getDestinationName() + "\" on channel " + getChannelId() + ")."; if (t instanceof InterruptedException) { Thread.currentThread().interrupt(); } else if (t instanceof ConnectException || t.getCause() != null && t.getCause() instanceof ConnectException) { if (isQueueEnabled()) { logger.warn(logMessage, t); } else { logger.error(logMessage, t); } } else { logger.debug(logMessage, t); } eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), message.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error sending message via TCP.", t)); } finally { eventController.dispatchEvent(new ConnectorCountEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE, SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket), (Boolean) null)); } return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse); }
From source file:com.mellanox.r4h.DFSClient.java
/** * Connect to the given datanode's datantrasfer port, and return * the resulting IOStreamPair. This includes encryption wrapping, etc. *//*w w w . ja v a 2 s . c o m*/ private IOStreamPair connectToDN(DatanodeInfo dn, int timeout, LocatedBlock lb) throws IOException { boolean success = false; Socket sock = null; try { sock = socketFactory.createSocket(); String dnAddr = dn.getXferAddr(getConf().getConnectToDnViaHostname()); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to datanode " + dnAddr); } NetUtils.connect(sock, NetUtils.createSocketAddr(dnAddr), timeout); sock.setSoTimeout(timeout); OutputStream unbufOut = NetUtils.getOutputStream(sock); InputStream unbufIn = NetUtils.getInputStream(sock); IOStreamPair ret = saslClient.newSocketSend(sock, unbufOut, unbufIn, this, lb.getBlockToken(), dn); success = true; return ret; } finally { if (!success) { IOUtils.closeSocket(sock); } } }
From source file:org.apache.hadoop.hdfs.DFSClient.java
/** * Connect to the given datanode's datantrasfer port, and return * the resulting IOStreamPair. This includes encryption wrapping, etc. *//*from w w w. java 2 s .c om*/ private IOStreamPair connectToDN(DatanodeInfo dn, int timeout, LocatedBlock lb) throws IOException { boolean success = false; Socket sock = null; try { sock = socketFactory.createSocket(); String dnAddr = dn.getXferAddr(getConf().connectToDnViaHostname); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to datanode " + dnAddr); } NetUtils.connect(sock, NetUtils.createSocketAddr(dnAddr), timeout); sock.setSoTimeout(timeout); OutputStream unbufOut = NetUtils.getOutputStream(sock); InputStream unbufIn = NetUtils.getInputStream(sock); IOStreamPair ret = saslClient.newSocketSend(sock, unbufOut, unbufIn, this, lb.getBlockToken(), dn); success = true; return ret; } finally { if (!success) { IOUtils.closeSocket(sock); } } }