List of usage examples for java.net Socket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:net.oneandone.sushi.fs.webdav.WebdavConnection.java
public static WebdavConnection open(Socket socket, HttpParams params) throws IOException { int linger;//from w w w. ja va 2s .c o m int buffersize; SessionInputBuffer input; SessionOutputBuffer output; socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params)); socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params)); linger = HttpConnectionParams.getLinger(params); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } buffersize = HttpConnectionParams.getSocketBufferSize(params); if (WebdavFilesystem.WIRE.isLoggable(Level.FINE)) { input = new LoggingSessionInputBuffer(socket, buffersize, params, WebdavFilesystem.WIRE); output = new LoggingSessionOutputBuffer(socket, buffersize, params, WebdavFilesystem.WIRE); } else { input = new SocketInputBuffer(socket, buffersize, params); output = new SocketOutputBuffer(socket, buffersize, params); } return new WebdavConnection(socket, input, output, params); }
From source file:org.apache.hadoop.hdfs.BlockReaderTestUtil.java
/** * Get a BlockReader for the given block. *///from w w w .j a v a 2 s. c om public static BlockReader getBlockReader(MiniDFSCluster cluster, LocatedBlock testBlock, int offset, int lenToRead) throws IOException { InetSocketAddress targetAddr = null; ExtendedBlock block = testBlock.getBlock(); DatanodeInfo[] nodes = testBlock.getLocations(); targetAddr = NetUtils.createSocketAddr(nodes[0].getXferAddr()); final DistributedFileSystem fs = cluster.getFileSystem(); return new BlockReaderFactory(fs.getClient().getConf()).setInetSocketAddress(targetAddr) .setExtendedBlock(block).setFileName(targetAddr.toString() + ":" + block.getBlockId()) .setBlockToken(testBlock.getBlockToken()).setStartOffset(offset).setLength(lenToRead) .setVerifyChecksum(true).setClientName("BlockReaderTestUtil").setDatanodeInfo(nodes[0]) .setClientCacheContext(ClientContext.getFromConf(fs.getConf())) .setCachingStrategy(CachingStrategy.newDefaultStrategy()).setConfiguration(fs.getConf()) .setAllowShortCircuitLocalReads(true).setTracer(FsTracer.get(fs.getConf())) .setRemotePeerFactory(new RemotePeerFactory() { @Override public SocketFactory getSocketFactory(Configuration conf) throws IOException { return NetUtils.getDefaultSocketFactory(conf); } @Override public Peer newConnectedPeer(InetSocketAddress addr, Token<BlockTokenIdentifier> blockToken, DatanodeID datanodeId) throws IOException { Peer peer = null; Socket sock = getSocketFactory(fs.getConf()).createSocket(); try { sock.connect(addr, HdfsServerConstants.READ_TIMEOUT); sock.setSoTimeout(HdfsServerConstants.READ_TIMEOUT); peer = TcpPeerServer.peerFromSocket(sock); } finally { if (peer == null) { IOUtils.closeQuietly(sock); } } return peer; } }).build(); }
From source file:org.apache.hadoop.hdfs.client.impl.BlockReaderTestUtil.java
/** * Get a BlockReader for the given block. *//*from w ww. ja va 2 s.c om*/ public static BlockReader getBlockReader(final DistributedFileSystem fs, LocatedBlock testBlock, int offset, long lenToRead) throws IOException { InetSocketAddress targetAddr = null; ExtendedBlock block = testBlock.getBlock(); DatanodeInfo[] nodes = testBlock.getLocations(); targetAddr = NetUtils.createSocketAddr(nodes[0].getXferAddr()); return new BlockReaderFactory(fs.getClient().getConf()).setInetSocketAddress(targetAddr).setBlock(block) .setFileName(targetAddr.toString() + ":" + block.getBlockId()) .setBlockToken(testBlock.getBlockToken()).setStartOffset(offset).setLength(lenToRead) .setVerifyChecksum(true).setClientName("BlockReaderTestUtil").setDatanodeInfo(nodes[0]) .setClientCacheContext(ClientContext.getFromConf(fs.getConf())) .setCachingStrategy(CachingStrategy.newDefaultStrategy()).setConfiguration(fs.getConf()) .setAllowShortCircuitLocalReads(true).setTracer(FsTracer.get(fs.getConf())) .setRemotePeerFactory(new RemotePeerFactory() { @Override public Peer newConnectedPeer(InetSocketAddress addr, Token<BlockTokenIdentifier> blockToken, DatanodeID datanodeId) throws IOException { Peer peer = null; Socket sock = NetUtils.getDefaultSocketFactory(fs.getConf()).createSocket(); try { sock.connect(addr, HdfsConstants.READ_TIMEOUT); sock.setSoTimeout(HdfsConstants.READ_TIMEOUT); peer = DFSUtilClient.peerFromSocket(sock); } finally { if (peer == null) { IOUtils.closeQuietly(sock); } } return peer; } }).build(); }
From source file:org.regenstrief.hl7.util.HL7IO.java
public static Socket connect(final String host, final int port, int nrRetries) throws UnknownHostException, IOException { final String prop = Util.getProperty(PROP_TIMEOUT_IN_MILLIS); final int timeout = prop == null ? -1 : Integer.parseInt(prop); while (nrRetries-- >= 0) { try {/*from w ww.jav a2s . c o m*/ final Socket rv = new Socket(host, port); if (timeout >= 0) { rv.setSoTimeout(timeout); } return rv; } catch (final UnknownHostException e) { e.fillInStackTrace(); //Utl.dp("connect failed: unknownHost:", host, port); throw e; } catch (final IOException e) { if (nrRetries < 0) { e.fillInStackTrace(); //Utl.dp("connect failed: connection refused:", host, port); throw e; } sleep(10); } } throw new HL7IOException("connect nr retries exceeded:" + host + "|" + port + "|" + nrRetries); }
From source file:org.planetcrypto.bitcoin.PlanetCryptoBitcoinMinerAPICommands.java
private static String process(String cmd, InetSocketAddress ip, int port) throws Exception { Socket socket = new Socket(); StringBuffer sb = new StringBuffer(); char buf[] = new char[MAXRECEIVESIZE]; int len = 0;/*from www.j ava2 s .c o m*/ //System.out.println("Attempting to send: " + cmd + " to: "+ ip.getHostAddress()+":"+port); try { //socket = new Socket(ip, port); socket.connect(ip, 2000); //System.out.println("Start Sleep"); //Thread.sleep(1000); //System.out.println("Stop Sleep"); socket.setSoTimeout(2000); //socket.(ip, port); //System.out.println(socket.getSoTimeout()); PrintStream ps = new PrintStream(socket.getOutputStream()); ps.print(cmd.toLowerCase().toCharArray()); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); while (0x80085 > 0) { len = isr.read(buf, 0, MAXRECEIVESIZE); if (len < 1) { break; } sb.append(buf, 0, len); if (buf[len - 1] == '\0') { break; } } //closeAll(); socket.close(); socket = null; } catch (IOException ioe) { System.err.println(ioe.toString() + ", " + ip.getHostName()); //closeAll(); socket.close(); socket = null; return "Failed to get information"; } String result = sb.toString(); //System.out.println(result); return result.replace("\0", ""); //jsonFactory(result); //System.out.println(result); }
From source file:org.apache.blur.console.util.NodeUtil.java
public static Map<String, Object> getZookeeperStatus() throws IOException { String[] connections = Config.getBlurConfig().get("blur.zookeeper.connection").split(","); Set<String> onlineZookeepers = new HashSet<String>(); Set<String> offlineZookeepers = new HashSet<String>(); for (String connection : connections) { Socket socket = null; InputStream response = null; OutputStream question = null; try {//w w w . ja v a 2 s. c o m URI parsedConnection = new URI("my://" + connection); String host = parsedConnection.getHost(); int port = parsedConnection.getPort() >= 0 ? parsedConnection.getPort() : 2181; byte[] reqBytes = new byte[4]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("ruok".getBytes()).getInt()); socket = new Socket(); socket.setSoLinger(false, 10); socket.setSoTimeout(20000); parsedConnection.getPort(); socket.connect(new InetSocketAddress(host, port)); response = socket.getInputStream(); question = socket.getOutputStream(); question.write(reqBytes); byte[] resBytes = new byte[4]; response.read(resBytes); String status = new String(resBytes); if (status.equals("imok")) { onlineZookeepers.add(connection); } else { offlineZookeepers.add(connection); } socket.close(); response.close(); question.close(); } catch (Exception e) { offlineZookeepers.add(connection); } finally { if (socket != null) { socket.close(); } if (response != null) { response.close(); } if (question != null) { question.close(); } } } Map<String, Object> data = new HashMap<String, Object>(); data.put("online", onlineZookeepers); data.put("offline", offlineZookeepers); return data; }
From source file:org.apache.hadoop.hdfs.server.blockmanagement.TestBlockTokenWithDFS.java
private static void tryRead(final Configuration conf, LocatedBlock lblock, boolean shouldSucceed) { InetSocketAddress targetAddr = null; IOException ioe = null;/*from w w w .j a v a2 s. c o m*/ BlockReader blockReader = null; ExtendedBlock block = lblock.getBlock(); try { DatanodeInfo[] nodes = lblock.getLocations(); targetAddr = NetUtils.createSocketAddr(nodes[0].getXferAddr()); blockReader = new BlockReaderFactory(new DFSClient.Conf(conf)) .setFileName(BlockReaderFactory.getFileName(targetAddr, "test-blockpoolid", block.getBlockId())) .setExtendedBlock(block).setBlockToken(lblock.getBlockToken()).setInetSocketAddress(targetAddr) .setStartOffset(0).setLength(-1).setVerifyChecksum(true).setClientName("TestBlockTokenWithDFS") .setDatanodeInfo(nodes[0]).setCachingStrategy(CachingStrategy.newDefaultStrategy()) .setClientCacheContext(ClientContext.getFromConf(conf)).setConfiguration(conf) .setTracer(FsTracer.get(conf)).setRemotePeerFactory(new RemotePeerFactory() { @Override public SocketFactory getSocketFactory(Configuration conf) throws IOException { return NetUtils.getDefaultSocketFactory(conf); } @Override public Peer newConnectedPeer(InetSocketAddress addr, Token<BlockTokenIdentifier> blockToken, DatanodeID datanodeId) throws IOException { Peer peer = null; Socket sock = getSocketFactory(conf).createSocket(); try { sock.connect(addr, HdfsServerConstants.READ_TIMEOUT); sock.setSoTimeout(HdfsServerConstants.READ_TIMEOUT); peer = TcpPeerServer.peerFromSocket(sock); } finally { if (peer == null) { IOUtils.closeSocket(sock); } } return peer; } }).build(); } catch (IOException ex) { ioe = ex; } finally { if (blockReader != null) { try { blockReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } } if (shouldSucceed) { Assert.assertNotNull("OP_READ_BLOCK: access token is invalid, " + "when it is expected to be valid", blockReader); } else { Assert.assertNotNull("OP_READ_BLOCK: access token is valid, " + "when it is expected to be invalid", ioe); Assert.assertTrue("OP_READ_BLOCK failed due to reasons other than access token: ", ioe instanceof InvalidBlockTokenException); } }
From source file:org.apache.hadoop.hdfs.server.namenode.TestAccessTokenWithDFS.java
private static void tryRead(Configuration conf, LocatedBlock lblock, boolean shouldSucceed) { InetSocketAddress targetAddr = null; Socket s = null; BlockReader blockReader = null;//from ww w .j ava2s . co m Block block = lblock.getBlock(); try { DatanodeInfo[] nodes = lblock.getLocations(); targetAddr = NetUtils.createSocketAddr(nodes[0].getName()); s = new Socket(); s.connect(targetAddr, HdfsConstants.READ_TIMEOUT); s.setSoTimeout(HdfsConstants.READ_TIMEOUT); blockReader = BlockReader.newBlockReader(s, targetAddr.toString() + ":" + block.getBlockId(), block.getBlockId(), lblock.getAccessToken(), block.getGenerationStamp(), 0, -1, conf.getInt("io.file.buffer.size", 4096)); } catch (IOException ex) { if (ex instanceof InvalidAccessTokenException) { assertFalse("OP_READ_BLOCK: access token is invalid, " + "when it is expected to be valid", shouldSucceed); return; } fail("OP_READ_BLOCK failed due to reasons other than access token"); } finally { if (s != null) { try { s.close(); } catch (IOException iex) { } finally { s = null; } } } if (blockReader == null) { fail("OP_READ_BLOCK failed due to reasons other than access token"); } assertTrue("OP_READ_BLOCK: access token is valid, " + "when it is expected to be invalid", shouldSucceed); }
From source file:org.apache.hadoop.hdfs.server.namenode.TestBlockTokenWithDFS.java
private static void tryRead(Configuration conf, LocatedBlock lblock, boolean shouldSucceed) { InetSocketAddress targetAddr = null; Socket s = null; DFSClient.BlockReader blockReader = null; Block block = lblock.getBlock();/*from w ww .j a v a 2s . c o m*/ try { DatanodeInfo[] nodes = lblock.getLocations(); targetAddr = NetUtils.createSocketAddr(nodes[0].getName()); s = new Socket(); s.connect(targetAddr, HdfsConstants.READ_TIMEOUT); s.setSoTimeout(HdfsConstants.READ_TIMEOUT); blockReader = DFSClient.BlockReader.newBlockReader(s, targetAddr.toString() + ":" + block.getBlockId(), block.getBlockId(), lblock.getBlockToken(), block.getGenerationStamp(), 0, -1, conf.getInt("io.file.buffer.size", 4096)); } catch (IOException ex) { if (ex instanceof InvalidBlockTokenException) { assertFalse("OP_READ_BLOCK: access token is invalid, " + "when it is expected to be valid", shouldSucceed); return; } fail("OP_READ_BLOCK failed due to reasons other than access token"); } finally { if (s != null) { try { s.close(); } catch (IOException iex) { } finally { s = null; } } } if (blockReader == null) { fail("OP_READ_BLOCK failed due to reasons other than access token"); } assertTrue("OP_READ_BLOCK: access token is valid, " + "when it is expected to be invalid", shouldSucceed); }
From source file:org.pentaho.di.trans.steps.mailvalidator.MailValidation.java
/** * Validate an email address This code is from : http://www.rgagnon.com/javadetails/java-0452.html * * @param email// w w w .j a va 2 s .com * address * @param sender * email address * @param default SMTP Server * @param timeout * for socket connection * @param deepCheck * (if we want to perform a SMTP check * @return true or false */ public static MailValidationResult isAddressValid(LogChannelInterface log, String address, String senderAddress, String defaultSMTPServer, int timeout, boolean deepCheck) { MailValidationResult result = new MailValidationResult(); if (!isRegExValid(address)) { result.setErrorMessage(BaseMessages.getString(PKG, "MailValidator.MalformedAddress", address)); return result; } // Find the separator for the domain name int pos = address.indexOf('@'); // If the address does not contain an '@', it's not valid if (pos == -1) { return result; } if (!deepCheck) { result.setValide(true); return result; } // Isolate the domain/machine name and get a list of mail exchangers String domain = address.substring(++pos); // Maybe user want to switch to a default SMTP server? // In that case, we will ignore the domain // extracted from email address ArrayList<String> mxList = new ArrayList<String>(); if (Const.isEmpty(defaultSMTPServer)) { try { mxList = getMX(domain); // Just because we can send mail to the domain, doesn't mean that the // address is valid, but if we can't, it's a sure sign that it isn't if (mxList == null || mxList.size() == 0) { result.setErrorMessage(BaseMessages.getString(PKG, "MailValidator.NoMachinesInDomain", domain)); return result; } } catch (Exception ex) { result.setErrorMessage( BaseMessages.getString(PKG, "MailValidator.ErrorGettingMachinesInDomain", ex.getMessage())); return result; } } else { mxList.add(defaultSMTPServer); } if (log.isDebug()) { log.logDebug(BaseMessages.getString(PKG, "MailValidator.ExchangersFound", "" + mxList.size())); } // Now, do the SMTP validation, try each mail exchanger until we get // a positive acceptance. It *MAY* be possible for one MX to allow // a message [store and forwarder for example] and another [like // the actual mail server] to reject it. This is why we REALLY ought // to take the preference into account. for (int mx = 0; mx < mxList.size(); mx++) { boolean valid = false; BufferedReader rdr = null; BufferedWriter wtr = null; Socket skt = null; try { String exhanger = mxList.get(mx); if (log.isDebug()) { log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.TryingExchanger", exhanger)); } int res; skt = new Socket(exhanger, 25); // set timeout (milliseconds) if (timeout > 0) { skt.setSoTimeout(timeout); } if (log.isDebug()) { log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.ConnectingTo", exhanger, "25", skt.isConnected() + "")); } rdr = new BufferedReader(new InputStreamReader(skt.getInputStream())); wtr = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream())); res = hear(rdr); if (res != 220) { throw new Exception(BaseMessages.getString(PKG, "MailValidator.InvalidHeader")); } // say HELLO it's me if (log.isDebug()) { log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.SayHello", domain)); } say(wtr, "EHLO " + domain); res = hear(rdr); if (res != 250) { throw new Exception("Not ESMTP"); } if (log.isDebug()) { log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.ServerReplied", "" + res)); } // validate the sender address if (log.isDebug()) { log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.CheckSender", senderAddress)); } say(wtr, "MAIL FROM: <" + senderAddress + ">"); res = hear(rdr); if (res != 250) { throw new Exception(BaseMessages.getString(PKG, "MailValidator.SenderRejected")); } if (log.isDebug()) { log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.SenderAccepted", "" + res)); } // Validate receiver if (log.isDebug()) { log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.CheckReceiver", address)); } say(wtr, "RCPT TO: <" + address + ">"); res = hear(rdr); // be polite say(wtr, "RSET"); hear(rdr); say(wtr, "QUIT"); hear(rdr); if (res != 250) { throw new Exception(BaseMessages.getString(PKG, "MailValidator.AddressNotValid", address)); } if (log.isDebug()) { log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.ReceiverAccepted", address, "" + res)); } valid = true; } catch (Exception ex) { // Do nothing but try next host result.setValide(false); result.setErrorMessage(ex.getMessage()); } finally { if (rdr != null) { try { rdr.close(); } catch (Exception e) { // ignore this } } if (wtr != null) { try { wtr.close(); } catch (Exception e) { // ignore this } } if (skt != null) { try { skt.close(); } catch (Exception e) { // ignore this } } if (valid) { result.setValide(true); result.setErrorMessage(null); if (log.isDebug()) { log.logDebug(className(), "============================================="); } return result; } } } if (log.isDebug()) { log.logDebug(className(), "============================================="); } return result; }