List of usage examples for java.net Socket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:org.apache.hadoop.hdfs.server.namenode.FileSystemProvider.java
/** * ?? ? ?? ? ? ?? ?./*from w ww . ja v a 2s.co m*/ * * @param blk LocatedBlock * @return ?? */ public static DatanodeInfo bestNode(LocatedBlock blk) { TreeSet<DatanodeInfo> deadNodes = new TreeSet<>(); DatanodeInfo chosenNode = null; int failures = 0; Socket socket = null; DatanodeInfo[] nodes = blk.getLocations(); if (nodes == null || nodes.length == 0) { throw new ServiceException("No nodes contain this block"); } while (socket == null) { if (chosenNode == null) { do { chosenNode = nodes[rand.nextInt(nodes.length)]; } while (deadNodes.contains(chosenNode)); } int index = rand.nextInt(nodes.length); chosenNode = nodes[index]; //just ping to check whether the node is alive InetSocketAddress address = NetUtils .createSocketAddr(chosenNode.getIpAddr() + ":" + chosenNode.getInfoPort()); try { socket = new Socket(); socket.connect(address, HdfsServerConstants.READ_TIMEOUT); socket.setSoTimeout(HdfsServerConstants.READ_TIMEOUT); } catch (IOException e) { deadNodes.add(chosenNode); try { socket.close(); } catch (IOException ex) { ex.printStackTrace(); } socket = null; failures++; } if (failures == nodes.length) { throw new ServiceException("Could not reach the block containing the data. Please try again"); } } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } return chosenNode; }
From source file:org.jboss.remoting.transport.http.HTTPServerInvoker.java
public void run() { try {//from w ww. ja v a 2 s . c o m if (newServerSocketFactory) { log.debug("got notice about new ServerSocketFactory"); try { log.debug("refreshing server socket"); refreshServerSocket(); } catch (IOException e) { log.debug("could not refresh server socket"); log.debug("message is: " + e.getMessage()); } log.debug("server socket refreshed"); } Socket socket = serverSocket.accept(); BufferedInputStream dataInput = null; BufferedOutputStream dataOutput = null; if (socket != null) { // tell the pool to start another thread to listen for more socket requests. httpThreadPool.run(this); try { boolean keepAlive = true; // start processing incoming request from client. will try to keep current connection alive socket.setKeepAlive(true); socket.setSoTimeout(keepAliveTimeout); DataInputStream realdataInput = new DataInputStream(socket.getInputStream()); DataOutputStream realdataOutput = new DataOutputStream(socket.getOutputStream()); while (keepAlive) { dataOutput = new BufferedOutputStream(realdataOutput, 512); dataInput = new BufferedInputStream(realdataInput, 512); keepAlive = processRequest(dataInput, dataOutput); } } catch (Throwable thr) { if (running) { log.error("Error processing incoming request.", thr); } } finally { if (dataInput != null) { try { dataInput.close(); } catch (Exception e) { log.warn("Error closing resource.", e); } } if (dataOutput != null) { try { dataOutput.close(); } catch (Exception e) { log.warn("Error closing resource.", e); } } try { socket.close(); } catch (Exception e) { log.warn("Error closing resource.", e); } } } } catch (Throwable thr) { if (running) { log.error("Error processing incoming request.", thr); } } }
From source file:org.mule.transport.soap.axis.extensions.MuleHttpSender.java
/** * Creates a socket connection to the SOAP server * * @param protocol "http" for standard, "https" for ssl. * @param host host name/*from www . j a va 2s .c o m*/ * @param port port to connect to * @param otherHeaders buffer for storing additional headers that need to be sent * @param useFullURL flag to indicate if the complete URL has to be sent * @throws java.io.IOException */ protected void getSocket(SocketHolder sockHolder, MessageContext msgContext, String protocol, String host, int port, int timeout, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception { @SuppressWarnings("unchecked") Hashtable<Object, Object> socketFactoryOptions = getOptions(); if (timeout > 0) { if (socketFactoryOptions == null) { socketFactoryOptions = new Hashtable<Object, Object>(); } socketFactoryOptions.put(DefaultSocketFactory.CONNECT_TIMEOUT, Integer.toString(timeout)); } SocketFactory factory = SocketFactoryFactory.getFactory(protocol, socketFactoryOptions); if (factory == null) { throw new IOException(Messages.getMessage("noSocketFactory", protocol)); } // log.fatal("Axis client: connect on socket: " + host + ":" + port); Socket sock = null; try { sock = factory.create(host, port, otherHeaders, useFullURL); } catch (Exception e) { Thread.sleep(1000); try { sock = factory.create(host, port, otherHeaders, useFullURL); } catch (Exception e1) { log.fatal("Axis client Failed: connect on socket: " + host + ":" + port, e); throw e; } } if (timeout > 0) { sock.setSoTimeout(timeout); } sockHolder.setSocket(sock); }
From source file:org.apache.hadoop.hdfs.server.datanode.DataXceiver.java
/** * Receive a block and write it to disk, it then notifies the namenode to * remove the copy from the source./*from w w w .j av a2 s . c o m*/ * * @param in The stream to read from * @throws IOException */ private void replaceBlock(DataInputStream in) throws IOException { /* read header */ long blockId = in.readLong(); Block block = new Block(blockId, dataXceiverServer.estimateBlockSize, in.readLong()); // block id & generation stamp String sourceID = Text.readString(in); // read del hint DatanodeInfo proxySource = new DatanodeInfo(); // read proxy source proxySource.readFields(in); Token<BlockTokenIdentifier> accessToken = new Token<BlockTokenIdentifier>(); accessToken.readFields(in); if (datanode.isBlockTokenEnabled) { try { datanode.blockTokenSecretManager.checkAccess(accessToken, null, block, BlockTokenSecretManager.AccessMode.REPLACE); } catch (InvalidToken e) { LOG.warn("Invalid access token in request from " + remoteAddress + " for OP_REPLACE_BLOCK for block " + block); sendResponse(s, (short) DataTransferProtocol.OP_STATUS_ERROR_ACCESS_TOKEN, datanode.socketWriteTimeout); return; } } if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to start LOG.warn("Not able to receive block " + blockId + " from " + s.getRemoteSocketAddress() + " because threads quota is exceeded."); sendResponse(s, (short) DataTransferProtocol.OP_STATUS_ERROR, datanode.socketWriteTimeout); return; } Socket proxySock = null; DataOutputStream proxyOut = null; short opStatus = DataTransferProtocol.OP_STATUS_SUCCESS; BlockReceiver blockReceiver = null; DataInputStream proxyReply = null; try { // get the output stream to the proxy InetSocketAddress proxyAddr = NetUtils.createSocketAddr(proxySource.getName()); proxySock = datanode.newSocket(); NetUtils.connect(proxySock, proxyAddr, datanode.socketTimeout); proxySock.setSoTimeout(datanode.socketTimeout); OutputStream baseStream = NetUtils.getOutputStream(proxySock, datanode.socketWriteTimeout); proxyOut = new DataOutputStream(new BufferedOutputStream(baseStream, SMALL_BUFFER_SIZE)); /* send request to the proxy */ proxyOut.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION); // transfer version proxyOut.writeByte(DataTransferProtocol.OP_COPY_BLOCK); // op code proxyOut.writeLong(block.getBlockId()); // block id proxyOut.writeLong(block.getGenerationStamp()); // block id accessToken.write(proxyOut); proxyOut.flush(); // receive the response from the proxy proxyReply = new DataInputStream( new BufferedInputStream(NetUtils.getInputStream(proxySock), BUFFER_SIZE)); short status = proxyReply.readShort(); if (status != DataTransferProtocol.OP_STATUS_SUCCESS) { if (status == DataTransferProtocol.OP_STATUS_ERROR_ACCESS_TOKEN) { throw new IOException("Copy block " + block + " from " + proxySock.getRemoteSocketAddress() + " failed due to access token error"); } throw new IOException( "Copy block " + block + " from " + proxySock.getRemoteSocketAddress() + " failed"); } // open a block receiver and check if the block does not exist blockReceiver = new BlockReceiver(block, proxyReply, proxySock.getRemoteSocketAddress().toString(), proxySock.getLocalSocketAddress().toString(), false, "", null, datanode); // receive a block blockReceiver.receiveBlock(null, null, null, null, dataXceiverServer.balanceThrottler, -1); // notify name node datanode.notifyNamenodeReceivedBlock(block, sourceID); LOG.info("Moved block " + block + " from " + s.getRemoteSocketAddress()); } catch (IOException ioe) { opStatus = DataTransferProtocol.OP_STATUS_ERROR; throw ioe; } finally { // receive the last byte that indicates the proxy released its thread resource if (opStatus == DataTransferProtocol.OP_STATUS_SUCCESS) { try { proxyReply.readChar(); } catch (IOException ignored) { } } // now release the thread resource dataXceiverServer.balanceThrottler.release(); // send response back try { sendResponse(s, opStatus, datanode.socketWriteTimeout); } catch (IOException ioe) { LOG.warn("Error writing reply back to " + s.getRemoteSocketAddress()); } IOUtils.closeStream(proxyOut); IOUtils.closeStream(blockReceiver); IOUtils.closeStream(proxyReply); } }
From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java
public void handleConnect(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI();/*from www . j a v a 2 s .c o m*/ try { if (log.isDebugEnabled()) log.debug("CONNECT: " + uri); InetAddrPort addrPort = new InetAddrPort(uri.toString()); if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) { sendForbid(request, response, uri); } else { HttpConnection http_connection = request.getHttpConnection(); http_connection.forceClose(); // Get the timeout int timeoutMs = 30000; Object maybesocket = http_connection.getConnection(); if (maybesocket instanceof Socket) { Socket s = (Socket) maybesocket; timeoutMs = s.getSoTimeout(); } // Create the tunnel HttpTunnel tunnel = newHttpTunnel(request, response, addrPort.getInetAddress(), addrPort.getPort(), timeoutMs); if (tunnel != null) { // TODO - need to setup semi-busy loop for IE. if (_tunnelTimeoutMs > 0) { tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs); if (maybesocket instanceof Socket) { Socket s = (Socket) maybesocket; s.setSoTimeout(_tunnelTimeoutMs); } } tunnel.setTimeoutMs(timeoutMs); customizeConnection(pathInContext, pathParams, request, tunnel.getSocket()); request.getHttpConnection().setHttpTunnel(tunnel); response.setStatus(HttpResponse.__200_OK); response.setContentLength(0); } request.setHandled(true); } } catch (Exception e) { LogSupport.ignore(log, e); response.sendError(HttpResponse.__500_Internal_Server_Error); } }
From source file:org.apache.hadoop.hdfs.server.namenode.NamenodeFsck.java
private void copyBlock(final DFSClient dfs, LocatedBlock lblock, OutputStream fos) throws Exception { int failures = 0; InetSocketAddress targetAddr = null; TreeSet<DatanodeInfo> deadNodes = new TreeSet<DatanodeInfo>(); BlockReader blockReader = null;// w w w . j a v a 2 s . co m ExtendedBlock block = lblock.getBlock(); while (blockReader == null) { DatanodeInfo chosenNode; try { chosenNode = bestNode(dfs, lblock.getLocations(), deadNodes); targetAddr = NetUtils.createSocketAddr(chosenNode.getXferAddr()); } catch (IOException ie) { if (failures >= DFSConfigKeys.DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_DEFAULT) { throw new IOException("Could not obtain block " + lblock, ie); } LOG.info("Could not obtain block from any node: " + ie); try { Thread.sleep(10000); } catch (InterruptedException iex) { } deadNodes.clear(); failures++; continue; } try { String file = BlockReaderFactory.getFileName(targetAddr, block.getBlockPoolId(), block.getBlockId()); blockReader = new BlockReaderFactory(dfs.getConf()).setFileName(file).setBlock(block) .setBlockToken(lblock.getBlockToken()).setStartOffset(0).setLength(-1) .setVerifyChecksum(true).setClientName("fsck").setDatanodeInfo(chosenNode) .setInetSocketAddress(targetAddr).setCachingStrategy(CachingStrategy.newDropBehind()) .setClientCacheContext(dfs.getClientContext()).setConfiguration(namenode.conf) .setRemotePeerFactory(new RemotePeerFactory() { @Override public Peer newConnectedPeer(InetSocketAddress addr, Token<BlockTokenIdentifier> blockToken, DatanodeID datanodeId) throws IOException { Peer peer = null; Socket s = NetUtils.getDefaultSocketFactory(conf).createSocket(); try { s.connect(addr, HdfsServerConstants.READ_TIMEOUT); s.setSoTimeout(HdfsServerConstants.READ_TIMEOUT); peer = TcpPeerServer.peerFromSocketAndKey(dfs.getSaslDataTransferClient(), s, NamenodeFsck.this, blockToken, datanodeId); } finally { if (peer == null) { IOUtils.closeQuietly(s); } } return peer; } }).build(); } catch (IOException ex) { // Put chosen node into dead list, continue LOG.info("Failed to connect to " + targetAddr + ":" + ex); deadNodes.add(chosenNode); } } byte[] buf = new byte[1024]; int cnt = 0; boolean success = true; long bytesRead = 0; try { while ((cnt = blockReader.read(buf, 0, buf.length)) > 0) { fos.write(buf, 0, cnt); bytesRead += cnt; } if (bytesRead != block.getNumBytes()) { throw new IOException("Recorded block size is " + block.getNumBytes() + ", but datanode returned " + bytesRead + " bytes"); } } catch (Exception e) { LOG.error("Error reading block", e); success = false; } finally { blockReader.close(); } if (!success) { throw new Exception("Could not copy block data for " + lblock.getBlock()); } }
From source file:org.mule.transport.http.HttpServerConnection.java
public HttpServerConnection(final Socket socket, String encoding, HttpConnector connector) throws IOException { super();// www .jav a 2 s. c o m if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } this.socket = socket; if (this.socket instanceof SSLSocket) { ((SSLSocket) socket).addHandshakeCompletedListener(this); } setSocketTcpNoDelay(); this.socket.setKeepAlive(connector.isKeepAlive()); if (connector.getReceiveBufferSize() != Connector.INT_VALUE_NOT_SET && socket.getReceiveBufferSize() != connector.getReceiveBufferSize()) { socket.setReceiveBufferSize(connector.getReceiveBufferSize()); } if (connector.getServerSoTimeout() != Connector.INT_VALUE_NOT_SET && socket.getSoTimeout() != connector.getServerSoTimeout()) { socket.setSoTimeout(connector.getServerSoTimeout()); } this.in = socket.getInputStream(); this.out = new DataOutputStream(socket.getOutputStream()); this.encoding = encoding; }
From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java
private void setSocketOptions(Socket s) throws SocketException { if (socketTimeout > 0) { s.setSoTimeout(socketTimeout); }//from ww w . ja va2 s. co m s.setTcpNoDelay(tcpNoDelay); // set socket tcpnodelay state if (linger > 0) { s.setSoLinger(true, linger); } }
From source file:org.apache.hadoop.hdfs.server.datanode.CachingDataXceiver.java
@Override public void replaceBlock(final ExtendedBlock block, final Token<BlockTokenIdentifier> blockToken, final String delHint, final DatanodeInfo proxySource) throws IOException { updateCurrentThreadName("Replacing block " + block + " from " + delHint); /* read header */ block.setNumBytes(dataXceiverServer.estimateBlockSize); if (datanode.isBlockTokenEnabled) { try {//from ww w . j ava 2 s .c om datanode.blockPoolTokenSecretManager.checkAccess(blockToken, null, block, BlockTokenSecretManager.AccessMode.REPLACE); } catch (InvalidToken e) { LOG.warn("Invalid access token in request from " + remoteAddress + " for OP_REPLACE_BLOCK for block " + block + " : " + e.getLocalizedMessage()); sendResponse(s, ERROR_ACCESS_TOKEN, "Invalid access token", dnConf.socketWriteTimeout); return; } } if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to start String msg = "Not able to receive block " + block.getBlockId() + " from " + s.getRemoteSocketAddress() + " because threads quota is exceeded."; LOG.warn(msg); sendResponse(s, ERROR, msg, dnConf.socketWriteTimeout); return; } Socket proxySock = null; DataOutputStream proxyOut = null; Status opStatus = SUCCESS; String errMsg = null; BlockReceiver blockReceiver = null; DataInputStream proxyReply = null; try { // get the output stream to the proxy InetSocketAddress proxyAddr = NetUtils.createSocketAddr(proxySource.getXferAddr()); proxySock = datanode.newSocket(); NetUtils.connect(proxySock, proxyAddr, dnConf.socketTimeout); proxySock.setSoTimeout(dnConf.socketTimeout); OutputStream baseStream = NetUtils.getOutputStream(proxySock, dnConf.socketWriteTimeout); proxyOut = new DataOutputStream(new BufferedOutputStream(baseStream, HdfsConstants.SMALL_BUFFER_SIZE)); /* send request to the proxy */ new Sender(proxyOut).copyBlock(block, blockToken); // receive the response from the proxy proxyReply = new DataInputStream( new BufferedInputStream(NetUtils.getInputStream(proxySock), HdfsConstants.IO_FILE_BUFFER_SIZE)); BlockOpResponseProto copyResponse = BlockOpResponseProto .parseFrom(HdfsProtoUtil.vintPrefixed(proxyReply)); if (copyResponse.getStatus() != SUCCESS) { if (copyResponse.getStatus() == ERROR_ACCESS_TOKEN) { throw new IOException("Copy block " + block + " from " + proxySock.getRemoteSocketAddress() + " failed due to access token error"); } throw new IOException( "Copy block " + block + " from " + proxySock.getRemoteSocketAddress() + " failed"); } // get checksum info about the block we're copying ReadOpChecksumInfoProto checksumInfo = copyResponse.getReadOpChecksumInfo(); DataChecksum remoteChecksum = DataTransferProtoUtil.fromProto(checksumInfo.getChecksum()); // open a block receiver and check if the block does not exist blockReceiver = new BlockReceiver(block, proxyReply, proxySock.getRemoteSocketAddress().toString(), proxySock.getLocalSocketAddress().toString(), null, 0, 0, 0, "", null, datanode, remoteChecksum); // receive a block blockReceiver.receiveBlock(null, null, null, null, dataXceiverServer.balanceThrottler, null); // notify name node datanode.notifyNamenodeReceivedBlock(block, delHint); LOG.info("Moved block " + block + " from " + s.getRemoteSocketAddress()); } catch (IOException ioe) { opStatus = ERROR; errMsg = "opReplaceBlock " + block + " received exception " + ioe; LOG.info(errMsg); throw ioe; } finally { // receive the last byte that indicates the proxy released its thread resource if (opStatus == SUCCESS) { try { proxyReply.readChar(); } catch (IOException ignored) { } } // now release the thread resource dataXceiverServer.balanceThrottler.release(); // send response back try { sendResponse(s, opStatus, errMsg, dnConf.socketWriteTimeout); } catch (IOException ioe) { LOG.warn("Error writing reply back to " + s.getRemoteSocketAddress()); } IOUtils.closeStream(proxyOut); IOUtils.closeStream(blockReceiver); IOUtils.closeStream(proxyReply); } // update metrics datanode.metrics.addReplaceBlockOp(elapsed()); }
From source file:net.jotel.ws.client.WebSocketClient.java
private Socket createSocket() throws IOException { Socket s; if (secure) { SocketFactory factory = SSLSocketFactory.getDefault(); s = factory.createSocket(host, port); } else {//from ww w. j a va2s . c om s = new Socket(host, port); } s.setKeepAlive(true); s.setSoTimeout(100000); return s; }