List of usage examples for java.net Socket connect
public void connect(SocketAddress endpoint, int timeout) throws IOException
From source file:de.ecclesia.kipeto.RepositoryResolver.java
/** * Ermittelt anhand der Default-Repository-URL die IP-Adresse der * Netzwerkkarte, die Verbindung zum Repository hat. *///from ww w . java 2s. c o m private String determinateLocalIP() throws IOException { Socket socket = null; try { int port; String hostname; if (isSftp()) { port = 22; hostname = getHostname(); } else { URL url = new URL(defaultRepositoryUrl); port = url.getPort() > -1 ? url.getPort() : url.getDefaultPort(); hostname = url.getHost(); } log.debug("Determinating local IP-Adress by connect to {}:{}", defaultRepositoryUrl, port); InetAddress address = Inet4Address.getByName(hostname); socket = new Socket(); socket.connect(new InetSocketAddress(address, port), 3000); InputStream stream = socket.getInputStream(); InetAddress localAddress = socket.getLocalAddress(); stream.close(); String localIp = localAddress.getHostAddress(); log.info("Local IP-Adress is {}", localIp); return localIp; } finally { if (socket != null) { socket.close(); } } }
From source file:com.cyberway.issue.crawler.fetcher.HeritrixProtocolSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the * given time limit.//from w w w .ja va 2s . co m * <p> * This method employs several techniques to circumvent the limitations * of older JREs that do not support connect timeout. When running in * JRE 1.4 or above reflection is used to call * Socket#connect(SocketAddress endpoint, int timeout) method. When * executing in older JREs 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 localAddress the local host name/IP to bind the socket to * @param localPort 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 * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * @throws ConnectTimeoutException if socket cannot be connected within the * given time limit * * @since 3.0 */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { // Below code is from the DefaultSSLProtocolSocketFactory#createSocket // method only it has workarounds to deal with pre-1.4 JVMs. I've // cut these out. if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } Socket socket = null; int timeout = params.getConnectionTimeout(); if (timeout == 0) { socket = createSocket(host, port, localAddress, localPort); } else { socket = new Socket(); ServerCache cache = (ServerCache) params.getParameter(FetchHTTP.SERVER_CACHE_KEY); InetAddress hostAddress = (cache != null) ? getHostAddress(cache, host) : null; InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port) : new InetSocketAddress(host, port); socket.bind(new InetSocketAddress(localAddress, localPort)); try { socket.connect(address, timeout); } catch (SocketTimeoutException e) { // Add timeout info. to the exception. throw new SocketTimeoutException( e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms."); } assert socket.isConnected() : "Socket not connected " + host; } return socket; }
From source file:com.t_oster.liblasercut.drivers.LaosCutter.java
@Override public void sendJob(LaserJob job, ProgressListener pl, List<String> warnings) throws IllegalJobException, Exception { currentFrequency = -1;//from w ww . jav a 2 s .c o m currentPower = -1; currentSpeed = -1; currentFocus = 0; currentPurge = false; currentVentilation = false; pl.progressChanged(this, 0); BufferedOutputStream out; ByteArrayOutputStream buffer = null; pl.taskChanged(this, "checking job"); checkJob(job); job.applyStartPoint(); if (!useTftp) { pl.taskChanged(this, "connecting"); Socket connection = new Socket(); connection.connect(new InetSocketAddress(hostname, port), 3000); out = new BufferedOutputStream(connection.getOutputStream()); pl.taskChanged(this, "sending"); } else { buffer = new ByteArrayOutputStream(); out = new BufferedOutputStream(buffer); pl.taskChanged(this, "buffering"); } this.writeJobCode(job, out, pl); if (this.isUseTftp()) { pl.taskChanged(this, "connecting"); TFTPClient tftp = new TFTPClient(); tftp.setDefaultTimeout(5000); //open a local UDP socket tftp.open(); pl.taskChanged(this, "sending"); ByteArrayInputStream bain = new ByteArrayInputStream(buffer.toByteArray()); tftp.sendFile(job.getName().replace(" ", "") + ".lgc", TFTP.BINARY_MODE, bain, this.getHostname(), this.getPort()); tftp.close(); bain.close(); if (debugFilename != null && !"".equals(debugFilename)) { pl.taskChanged(this, "writing " + debugFilename); FileOutputStream o = new FileOutputStream(new File(debugFilename)); o.write(buffer.toByteArray()); o.close(); } pl.taskChanged(this, "sent."); } pl.progressChanged(this, 100); }
From source file:org.parosproxy.paros.network.SSLConnector.java
/** * Attempts to get a new socket connection to the given host within the * given time limit./*from www .j a v a 2 s . c o m*/ * * @param host * the host name/IP * @param port * the port on the host * @param localAddress * the local host name/IP to bind the socket to * @param localPort * 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 * @throws ConnectTimeoutException */ @Override public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { InetAddress hostAddress = getCachedMisconfiguredHost(host, port); if (hostAddress != null) { return clientSSLSockFactory.createSocket(hostAddress, port, localAddress, localPort); } try { SSLSocket sslSocket = (SSLSocket) clientSSLSockFactory.createSocket(host, port, localAddress, localPort); sslSocket.startHandshake(); return sslSocket; } catch (SSLException e) { if (!e.getMessage().contains(CONTENTS_UNRECOGNIZED_NAME_EXCEPTION)) { throw e; } hostAddress = InetAddress.getByName(host); cacheMisconfiguredHost(host, port, hostAddress); return clientSSLSockFactory.createSocket(hostAddress, port, localAddress, localPort); } } Socket socket = clientSSLSockFactory.createSocket(); SocketAddress localAddr = new InetSocketAddress(localAddress, localPort); socket.bind(localAddr); SocketAddress remoteAddr = new InetSocketAddress(host, port); socket.connect(remoteAddr, timeout); return socket; }
From source file:org.apache.hadoop.hive.metastore.MetaStoreUtils.java
/** * A simple connect test to make sure that the metastore is up * @throws Exception//from w w w. j av a 2 s.com */ private static void loopUntilHMSReady(int port) throws Exception { int retries = 0; Exception exc = null; while (true) { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(port), 5000); socket.close(); return; } catch (Exception e) { if (retries++ > 60) { //give up exc = e; break; } Thread.sleep(1000); } } // something is preventing metastore from starting // print the stack from all threads for debugging purposes LOG.error("Unable to connect to metastore server: " + exc.getMessage()); LOG.info("Printing all thread stack traces for debugging before throwing exception."); LOG.info(getAllThreadStacksAsString()); throw exc; }
From source file:hornet.framework.clamav.service.ClamAVCheckService.java
/** * Ouvre la socket avec dlai max.//w ww. j ava2s .c o m * * @param command * le type de rponse ClamAV * @return null si le dlai imparti la connexion a t atteint * @throws IOException * si erreur autre que timeout atteint */ private Socket connect(final TypeResponse command) throws IOException { Socket socket = null; ClamAVCheckService.LOGGER.debug("Ouverture du socket pour la commande : '{}'", command); final InetSocketAddress hostport = new InetSocketAddress(this.clamAVServer, this.clamAVPort); socket = new Socket(); // connexion avec timeout try { socket.connect(hostport, this.connectTimeout); } catch (final ConnectException e) { ClamAVCheckService.LOGGER.error("Timeout systme lors de la connexion ", e); return null; } catch (final SocketTimeoutException e) { ClamAVCheckService.LOGGER.error("Timeout atteint lors de la connexion ", e); return null; } return socket; }
From source file:org.apache.giraph.zk.ZooKeeperManager.java
/** * If this task has been selected, online a ZooKeeper server. Otherwise, * wait until this task knows that the ZooKeeper servers have been onlined. *//*from w w w.j a v a 2s.c om*/ public void onlineZooKeeperServers() { Integer taskId = zkServerPortMap.get(myHostname); if ((taskId != null) && (taskId.intValue() == taskPartition)) { File zkDirFile = new File(this.zkDir); try { if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Trying to delete old " + "directory " + this.zkDir); } FileUtils.deleteDirectory(zkDirFile); } catch (IOException e) { LOG.warn("onlineZooKeeperServers: Failed to delete " + "directory " + this.zkDir, e); } generateZooKeeperConfigFile(new ArrayList<String>(zkServerPortMap.keySet())); ProcessBuilder processBuilder = new ProcessBuilder(); List<String> commandList = Lists.newArrayList(); String javaHome = System.getProperty("java.home"); if (javaHome == null) { throw new IllegalArgumentException("onlineZooKeeperServers: java.home is not set!"); } commandList.add(javaHome + "/bin/java"); String zkJavaOptsString = GiraphConstants.ZOOKEEPER_JAVA_OPTS.get(conf); String[] zkJavaOptsArray = zkJavaOptsString.split(" "); if (zkJavaOptsArray != null) { commandList.addAll(Arrays.asList(zkJavaOptsArray)); } commandList.add("-cp"); Path fullJarPath = new Path(conf.get(GiraphConstants.ZOOKEEPER_JAR)); commandList.add(fullJarPath.toString()); commandList.add(QuorumPeerMain.class.getName()); commandList.add(configFilePath); processBuilder.command(commandList); File execDirectory = new File(zkDir); processBuilder.directory(execDirectory); processBuilder.redirectErrorStream(true); if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Attempting to " + "start ZooKeeper server with command " + commandList + " in directory " + execDirectory.toString()); } try { synchronized (this) { zkProcess = processBuilder.start(); zkProcessCollector = new StreamCollector(zkProcess.getInputStream()); zkProcessCollector.start(); } Runnable runnable = new Runnable() { public void run() { LOG.info("run: Shutdown hook started."); synchronized (this) { if (zkProcess != null) { LOG.warn("onlineZooKeeperServers: " + "Forced a shutdown hook kill of the " + "ZooKeeper process."); zkProcess.destroy(); int exitCode = -1; try { exitCode = zkProcess.waitFor(); } catch (InterruptedException e) { LOG.warn("run: Couldn't get exit code."); } LOG.info("onlineZooKeeperServers: ZooKeeper process exited " + "with " + exitCode + " (note that 143 " + "typically means killed)."); } } } }; Runtime.getRuntime().addShutdownHook(new Thread(runnable)); LOG.info("onlineZooKeeperServers: Shutdown hook added."); } catch (IOException e) { LOG.error("onlineZooKeeperServers: Failed to start " + "ZooKeeper process", e); throw new RuntimeException(e); } // Once the server is up and running, notify that this server is up // and running by dropping a ready stamp. int connectAttempts = 0; final int maxConnectAttempts = conf.getZookeeperConnectionAttempts(); while (connectAttempts < maxConnectAttempts) { try { if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Connect attempt " + connectAttempts + " of " + maxConnectAttempts + " max trying to connect to " + myHostname + ":" + zkBasePort + " with poll msecs = " + pollMsecs); } InetSocketAddress zkServerAddress = new InetSocketAddress(myHostname, zkBasePort); Socket testServerSock = new Socket(); testServerSock.connect(zkServerAddress, 5000); if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Connected to " + zkServerAddress + "!"); } break; } catch (SocketTimeoutException e) { LOG.warn("onlineZooKeeperServers: Got " + "SocketTimeoutException", e); } catch (ConnectException e) { LOG.warn("onlineZooKeeperServers: Got " + "ConnectException", e); } catch (IOException e) { LOG.warn("onlineZooKeeperServers: Got " + "IOException", e); } ++connectAttempts; try { Thread.sleep(pollMsecs); } catch (InterruptedException e) { LOG.warn("onlineZooKeeperServers: Sleep of " + pollMsecs + " interrupted - " + e.getMessage()); } } if (connectAttempts == maxConnectAttempts) { throw new IllegalStateException( "onlineZooKeeperServers: Failed to connect in " + connectAttempts + " tries!"); } Path myReadyPath = new Path(serverDirectory, myHostname + HOSTNAME_TASK_SEPARATOR + taskPartition); try { if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Creating my filestamp " + myReadyPath); } fs.createNewFile(myReadyPath); } catch (IOException e) { LOG.error("onlineZooKeeperServers: Failed (maybe previous " + "task failed) to create filestamp " + myReadyPath, e); } } else { List<String> foundList = new ArrayList<String>(); int readyRetrievalAttempt = 0; while (true) { try { FileStatus[] fileStatusArray = fs.listStatus(serverDirectory); foundList.clear(); if ((fileStatusArray != null) && (fileStatusArray.length > 0)) { for (int i = 0; i < fileStatusArray.length; ++i) { String[] hostnameTaskArray = fileStatusArray[i].getPath().getName() .split(HOSTNAME_TASK_SEPARATOR); if (hostnameTaskArray.length != 2) { throw new RuntimeException("getZooKeeperServerList: Task 0 failed " + "to parse " + fileStatusArray[i].getPath().getName()); } foundList.add(hostnameTaskArray[0]); } if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Got " + foundList + " " + foundList.size() + " hosts from " + fileStatusArray.length + " ready servers when " + serverCount + " required (polling period is " + pollMsecs + ") on attempt " + readyRetrievalAttempt); } if (foundList.containsAll(zkServerPortMap.keySet())) { break; } } else { if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperSErvers: Empty " + "directory " + serverDirectory + ", waiting " + pollMsecs + " msecs."); } } Thread.sleep(pollMsecs); ++readyRetrievalAttempt; } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { LOG.warn("onlineZooKeeperServers: Strange interrupt from " + e.getMessage(), e); } } } }
From source file:org.swiftp.server.ProxyConnector.java
/** * Connects an outgoing socket to the proxy and authenticates, creating an account if * necessary./*from w w w . ja va 2 s . com*/ */ private Socket newAuthedSocket(String hostname, int port) { if (hostname == null) { myLog.i("newAuthedSocket can't connect to null host"); return null; } JSONObject json = new JSONObject(); // String secret = retrieveSecret(); Socket socket; OutputStream out = null; InputStream in = null; try { myLog.d("Opening proxy connection to " + hostname + ":" + port); socket = new Socket(); socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT); json.put("android_id", Util.getAndroidId()); json.put("swiftp_version", Util.getVersion()); json.put("action", "login"); out = socket.getOutputStream(); in = socket.getInputStream(); int numBytes; out.write(json.toString().getBytes(ENCODING)); myLog.l(Log.DEBUG, "Sent login request"); // Read and parse the server's response byte[] bytes = new byte[IN_BUF_SIZE]; // Here we assume that the server's response will all be contained in // a single read, which may be unsafe for large responses numBytes = in.read(bytes); if (numBytes == -1) { myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response"); return null; } else if (numBytes == 0) { myLog.l(Log.INFO, "Short network read waiting for auth, quitting"); return null; } json = new JSONObject(new String(bytes, 0, numBytes, ENCODING)); if (checkAndPrintJsonError(json)) { return null; } myLog.d("newAuthedSocket successful"); return socket; } catch (Exception e) { myLog.i("Exception during proxy connection or authentication: " + e); return null; } }
From source file:com.cong.chenchong.wifi.manager.ProxyConnector.java
/** * Connects an outgoing socket to the proxy and authenticates, creating an account * if necessary.// w ww .j av a2s . com */ private Socket newAuthedSocket(String hostname, int port) { if (hostname == null) { //myLog.i("newAuthedSocket can't connect to null host"); return null; } JSONObject json = new JSONObject(); //String secret = retrieveSecret(); Socket socket; OutputStream out = null; InputStream in = null; try { //myLog.d("Opening proxy connection to " + hostname + ":" + port); socket = new Socket(); socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT); json.put("android_id", RemoteUtil.getAndroidId()); json.put("swiftp_version", RemoteUtil.getVersion()); json.put("action", "login"); out = socket.getOutputStream(); in = socket.getInputStream(); int numBytes; out.write(json.toString().getBytes(ENCODING)); //myLog.l(Log.DEBUG, "Sent login request"); // Read and parse the server's response byte[] bytes = new byte[IN_BUF_SIZE]; // Here we assume that the server's response will all be contained in // a single read, which may be unsafe for large responses numBytes = in.read(bytes); if (numBytes == -1) { //myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response"); return null; } else if (numBytes == 0) { //myLog.l(Log.INFO, "Short network read waiting for auth, quitting"); return null; } json = new JSONObject(new String(bytes, 0, numBytes, ENCODING)); if (checkAndPrintJsonError(json)) { return null; } //myLog.d("newAuthedSocket successful"); return socket; } catch (Exception e) { //myLog.i("Exception during proxy connection or authentication: " + e); return null; } }
From source file:com.cbsb.ftpserv.ProxyConnector.java
/** * Connects an outgoing socket to the proxy and authenticates, creating an account * if necessary.//from w w w . j ava2 s. c o m */ private Socket newAuthedSocket(String hostname, int port) { if (hostname == null) { myLog.i("newAuthedSocket can't connect to null host"); return null; } JSONObject json = new JSONObject(); //String secret = retrieveSecret(); Socket socket; OutputStream out = null; InputStream in = null; try { myLog.d("Opening proxy connection to " + hostname + ":" + port); socket = new Socket(); socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT); json.put("android_id", Util.getAndroidId()); json.put("swiftp_version", Util.getVersion()); json.put("action", "login"); out = socket.getOutputStream(); in = socket.getInputStream(); int numBytes; out.write(json.toString().getBytes(ENCODING)); myLog.l(Log.DEBUG, "Sent login request"); // Read and parse the server's response byte[] bytes = new byte[IN_BUF_SIZE]; // Here we assume that the server's response will all be contained in // a single read, which may be unsafe for large responses numBytes = in.read(bytes); if (numBytes == -1) { myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response"); return null; } else if (numBytes == 0) { myLog.l(Log.INFO, "Short network read waiting for auth, quitting"); return null; } json = new JSONObject(new String(bytes, 0, numBytes, ENCODING)); if (checkAndPrintJsonError(json)) { return null; } myLog.d("newAuthedSocket successful"); return socket; } catch (Exception e) { myLog.i("Exception during proxy connection or authentication: " + e); return null; } }