List of usage examples for java.net Socket connect
public void connect(SocketAddress endpoint) throws IOException
From source file:it.jnrpe.client.JNRPEClient.java
/** * Inovoke a command installed in JNRPE. * /*w w w .ja v a 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:org.kepler.util.sql.HSQL.java
/** Get the port for a database name. If dbPort is outside the range of * ports previously used for Kepler (9001-9010), then dbPort is returned. * If the port file exists in the database directory, then the port in * this file is returned. Otherwise, this method chooses a random port, * writes it to the port file, and returns the value. The port file is * removed when the server is shut down either in shutdownServers(), or * disconnect()./*from w ww. j a v a 2 s .co m*/ */ @Override protected synchronized String _getPort(String dbPort, String dbName, String hostName) throws IOException { boolean choseRandom = false; // make sure the host name is set if (hostName != null && !hostName.trim().isEmpty()) { // check if db port is not null, and in 9001-9010 if (dbPort == null || dbPort.trim().isEmpty()) { choseRandom = true; } else { final int port = Integer.valueOf(dbPort); if (port >= 9001 && port <= 9010) { choseRandom = true; } } } if (choseRandom) { dbPort = null; // see if port file exists for this database final File portFile = new File(dbName + _PORT_FILE_EXTENSION); if (portFile.exists()) { final Properties properties = _readPropertiesFile(portFile); dbPort = properties.getProperty(_PORT_FILE_PASSWORD_PROP_NAME); } // see if the port file existed and we're already using this port. // NOTE: by keeping a set of ports we've randomly chosen and checking // it here, we can handle the (unlikely) case where the same port is // in more than one port file. if (dbPort != null) { String existingDbName = _serverPortToName.get(dbPort); // see if the port is associated with a database if (existingDbName == null) { // add the mapping _serverPortToName.put(dbPort, dbName); } // see if the port is associated with a different database else if (!dbName.equals(existingDbName)) { // set to null so we chose a different port. dbPort = null; } } if (dbPort == null) { int port = -1; int tries = 10; while (tries > 0) { // pick random port between 10,000 and 60,000 port = _random.nextInt(50000) + 10000; // see the port is in use final Socket socket = new Socket(); final InetSocketAddress addr = new InetSocketAddress("localhost", port); try { socket.connect(addr); socket.close(); //System.out.println("port " + port + " already in use. tries = " + tries); tries--; } catch (IOException e) { // connection failed //System.out.println("port " + port + " not in use."); break; } } if (tries == 0) { throw new IOException("Could not choose random port for HSQL server."); } dbPort = String.valueOf(port); _serverPortToName.put(dbPort, dbName); // write to port file final Properties properties = new Properties(); properties.put(_PORT_FILE_PASSWORD_PROP_NAME, dbPort); _writePropertiesFile(portFile, properties); } } return dbPort; }
From source file:android.core.SSLSocketTest.java
/** * Does a number of HTTPS requests on some host and consumes the response. * We don't use the HttpsUrlConnection class, but do this on our own * with the SSLSocket class. This gives us a chance to test the basic * behavior of SSL./* w w w .j av a 2s . c o m*/ * * @param host The host name the request is being sent to. * @param port The port the request is being sent to. * @param path The path being requested (e.g. "/index.html"). * @param outerLoop The number of times we reconnect and do the request. * @param innerLoop The number of times we do the request for each * connection (using HTTP keep-alive). * @param delay The delay after each request (in seconds). * @throws IOException When a problem occurs. */ private void fetch(SSLSocketFactory socketFactory, String host, int port, boolean secure, String path, int outerLoop, int innerLoop, int delay, int timeout) throws IOException { InetSocketAddress address = new InetSocketAddress(host, port); for (int i = 0; i < outerLoop; i++) { // Connect to the remote host Socket socket = secure ? socketFactory.createSocket() : new Socket(); if (timeout >= 0) { socket.setKeepAlive(true); socket.setSoTimeout(timeout * 1000); } socket.connect(address); // Get the streams OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output); try { DataInputStream input = new DataInputStream(socket.getInputStream()); try { for (int j = 0; j < innerLoop; j++) { android.util.Log.d("SSLSocketTest", "GET https://" + host + path + " HTTP/1.1"); // Send a request writer.println("GET https://" + host + path + " HTTP/1.1\r"); writer.println("Host: " + host + "\r"); writer.println("Connection: " + (j == innerLoop - 1 ? "Close" : "Keep-Alive") + "\r"); writer.println("\r"); writer.flush(); int length = -1; boolean chunked = false; String line = input.readLine(); if (line == null) { throw new IOException("No response from server"); // android.util.Log.d("SSLSocketTest", "No response from server"); } // Consume the headers, check content length and encoding type while (line != null && line.length() != 0) { // System.out.println(line); int dot = line.indexOf(':'); if (dot != -1) { String key = line.substring(0, dot).trim(); String value = line.substring(dot + 1).trim(); if ("Content-Length".equalsIgnoreCase(key)) { length = Integer.valueOf(value); } else if ("Transfer-Encoding".equalsIgnoreCase(key)) { chunked = "Chunked".equalsIgnoreCase(value); } } line = input.readLine(); } assertTrue("Need either content length or chunked encoding", length != -1 || chunked); // Consume the content itself if (chunked) { length = Integer.parseInt(input.readLine(), 16); while (length != 0) { byte[] buffer = new byte[length]; input.readFully(buffer); input.readLine(); length = Integer.parseInt(input.readLine(), 16); } input.readLine(); } else { byte[] buffer = new byte[length]; input.readFully(buffer); } // Sleep for the given number of seconds try { Thread.sleep(delay * 1000); } catch (InterruptedException ex) { // Shut up! } } } finally { input.close(); } } finally { writer.close(); } // Close the connection socket.close(); } }
From source file:com.smartmarmot.dbforbix.config.Config.java
/** * Send request to Zabbix Server:/*from w w w .ja v a2 s . c o m*/ * @param host - Zabbix Server * @param port - Zabbix Server Port * @param json - body of request in json format * @return - body of response in json format */ public String requestZabbix(String host, int port, String json) { byte[] response = new byte[2048]; Socket zabbix = null; OutputStreamWriter out = null; InputStream in = null; byte[] data = null; String resp = new String(); try { zabbix = new Socket(); //TODO socket timeout has to be read from config file zabbix.setSoTimeout(30000); zabbix.connect(new InetSocketAddress(host, port)); OutputStream os = zabbix.getOutputStream(); data = getRequestToZabbixServer(json); //send request os.write(data); os.flush(); //read response in = zabbix.getInputStream(); //convert response to string (expecting json) int pos1 = 13; int bRead = 0; while (true) { bRead = in.read(response); //LOG.debug("read="+read+"\nresponse="+new String(response)); if (bRead <= 0) break; //remove binary header resp += new String(Arrays.copyOfRange(response, pos1, bRead)); pos1 = 0; } //LOG.debug("requestZabbix(): resp: "+ resp); //resp=resp.substring(13);//remove binary header if (resp.isEmpty()) throw new ZBXBadResponseException("Zabbix Server (" + host + ":" + port + ") has returned empty response for request:\n" + json); } catch (ZBXBadResponseException respEx) { LOG.error(respEx.getLocalizedMessage()); } catch (Exception ex) { LOG.error("Error getting data from Zabbix server (" + host + ":" + port + "): " + ex.getMessage()); } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) try { out.close(); } catch (IOException e) { } if (zabbix != null) try { zabbix.close(); } catch (IOException e) { } } return resp; }
From source file:hudson.cli.CLI.java
/** * @deprecated Specific to {@link Mode#REMOTING}. */// ww w.j a v a 2s . co m @Deprecated private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException { LOGGER.log(FINE, "Trying to connect directly via Remoting over TCP/IP to {0}", clip.endpoint); if (authorization != null) { LOGGER.warning("-auth ignored when using JNLP agent port"); } final Socket s = new Socket(); // this prevents a connection from silently terminated by the router in between or the other peer // and that goes without unnoticed. However, the time out is often very long (for example 2 hours // by default in Linux) that this alone is enough to prevent that. s.setKeepAlive(true); // we take care of buffering on our own s.setTcpNoDelay(true); OutputStream out; if (httpsProxyTunnel != null) { String[] tokens = httpsProxyTunnel.split(":"); LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port", new Object[] { tokens[0], tokens[1] }); s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1]))); PrintStream o = new PrintStream(s.getOutputStream()); o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort() + " HTTP/1.0\r\n\r\n"); // read the response from the proxy ByteArrayOutputStream rsp = new ByteArrayOutputStream(); while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) { int ch = s.getInputStream().read(); if (ch < 0) throw new IOException("Failed to read the HTTP proxy response: " + rsp); rsp.write(ch); } String head = new BufferedReader(new StringReader(rsp.toString("ISO-8859-1"))).readLine(); if (head == null) { throw new IOException("Unexpected empty response"); } if (!(head.startsWith("HTTP/1.0 200 ") || head.startsWith("HTTP/1.1 200 "))) { s.close(); LOGGER.log(Level.SEVERE, "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP."); throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp); } // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well. // So instead of relying on it, we'll just send the close command and then let the server // cut their side, then close the socket after the join. out = new SocketOutputStream(s) { @Override public void close() throws IOException { // ignore } }; } else { s.connect(clip.endpoint, 3000); out = SocketChannelStream.out(s); } closables.add(new Closeable() { public void close() throws IOException { s.close(); } }); Connection c = new Connection(SocketChannelStream.in(s), out); switch (clip.version) { case 1: DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI-connect"); // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor. break; case 2: DataInputStream dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI2-connect"); String greeting = dis.readUTF(); if (!greeting.equals("Welcome")) throw new IOException("Handshaking failed: " + greeting); try { byte[] secret = c.diffieHellman(false).generateSecret(); SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret, 128 / 8), "AES"); c = c.encryptConnection(sessionKey, "AES/CFB8/NoPadding"); // validate the instance identity, so that we can be sure that we are talking to the same server // and there's no one in the middle. byte[] signature = c.readByteArray(); if (clip.identity != null) { Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(clip.getIdentity()); verifier.update(secret); if (!verifier.verify(signature)) throw new IOException("Server identity signature validation failed."); } } catch (GeneralSecurityException e) { throw (IOException) new IOException("Failed to negotiate transport security").initCause(e); } } return new Channel("CLI connection to " + jenkins, pool, new BufferedInputStream(c.in), new BufferedOutputStream(c.out)); }
From source file:org.jivesoftware.openfire.clearspace.ClearspaceManager.java
private List<String> getServerInterfaces() { List<String> bindInterfaces = new ArrayList<String>(); String interfaceName = JiveGlobals.getXMLProperty("network.interface"); String bindInterface = null;/*from www . j a va2 s . co m*/ if (interfaceName != null) { if (interfaceName.trim().length() > 0) { bindInterface = interfaceName; } } int adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090); int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091); if (bindInterface == null) { try { Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netInterface : Collections.list(nets)) { Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); for (InetAddress address : Collections.list(addresses)) { if ("127.0.0.1".equals(address.getHostAddress())) { continue; } if (address.getHostAddress().startsWith("0.")) { continue; } Socket socket = new Socket(); InetSocketAddress remoteAddress = new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort); try { socket.connect(remoteAddress); bindInterfaces.add(address.getHostAddress()); break; } catch (IOException e) { // Ignore this address. Let's hope there is more addresses to validate } } } } catch (SocketException e) { // We failed to discover a valid IP address where the admin console is running return null; } } else { bindInterfaces.add(bindInterface); } return bindInterfaces; }
From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java
@Override public void run() { Socket socket = null;/*from w ww .j ava 2 s . co m*/ try { if (myPrintOutput) { System.out.println("Opening server socket on port " + 10201); } ServerSocket serverSocket = new ServerSocket(10201); socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); inputStream = new BufferedInputStream(inputStream); MinLLPReader minLLPReader = new MinLLPReader(inputStream); Socket outSocket = null; if (myPrintOutput) { System.out.println("Accepting connection from " + socket.getInetAddress().getHostAddress()); } for (int i = 0; i < myIterations; i++) { String messageText; do { messageText = minLLPReader.getMessage(); Thread.sleep(250); } while (messageText == null); if (myPrintOutput) { System.out.println("Received message:\r\n" + messageText + "\r\n"); } MSH inboundHeader = (MSH) myParser.parse(messageText).get("MSH"); String controlId = inboundHeader.getMessageControlID().encode(); if (StringUtils.isNotBlank(controlId) && myControlIdsToIgnore.indexOf(controlId) > -1) { Message replyAck = DefaultApplication.makeACK(inboundHeader); new MinLLPWriter(socket.getOutputStream()).writeMessage(myParser.encode(replyAck)); } else { System.out.println("Ignoring message with control ID " + controlId); } for (Map.Entry<String, String> next : mySubstitutions.entrySet()) { messageText = messageText.replace(next.getKey(), next.getValue()); } if ((outSocket != null) && myAlwaysCreateNewOutboundConnection) { outSocket.close(); outSocket = null; } if (outSocket == null) { if (myPrintOutput) { System.out.println("Opening outbound connection to port " + 10200); } outSocket = new Socket(); outSocket.connect(new InetSocketAddress("localhost", 10200)); } if (myPrintOutput) { System.out.println("Sending message from port " + outSocket.getLocalPort() + ":\r\n" + messageText + "\r\n"); } new MinLLPWriter(outSocket.getOutputStream()).writeMessage(messageText); new MinLLPReader(outSocket.getInputStream()).getMessage(); } serverSocket.close(); socket.close(); myStopped = true; } catch (Exception e) { myStopped = true; e.printStackTrace(); } }
From source file:com.devoteam.srit.xmlloader.http.bio.BIOChannelHttp.java
/** Open a connexion to each Stack */ public boolean open() throws Exception { if (this.secure) { StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TLS, StackFactory.PROTOCOL_HTTP); } else {/*from ww w . j av a 2s . c o m*/ StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TCP, StackFactory.PROTOCOL_HTTP); } this.startTimestamp = System.currentTimeMillis(); if (null != this.socketServerHttp) { ThreadPool.reserve().start((BIOSocketServerHttp) socketServerHttp); } else { String host = this.getRemoteHost(); int port = this.getRemotePort(); DefaultHttpClientConnection defaultHttpClientConnection = new DefaultHttpClientConnection(); Socket socket; if (this.secure) { // Create a trust manager that does not validate certificate chains like the default TrustManager TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, null); socket = sslContext.getSocketFactory().createSocket(); // read all properties for the TCP socket Config.getConfigForTCPSocket(socket, true); } else { // // Create a TCP non secure socket // socket = new Socket(); // read all properties for the TCP socket Config.getConfigForTCPSocket(socket, false); } // // Bind the socket to the local address // String localHost = this.getLocalHost(); int localPort = initialLocalport; if (null != localHost) { socket.bind(new InetSocketAddress(localHost, localPort)); } else { socket.bind(new InetSocketAddress(localPort)); } socket.setReceiveBufferSize(65536); socket.connect(new InetSocketAddress(host, port)); this.setLocalPort(socket.getLocalPort()); HttpParams params = new BasicHttpParams(); defaultHttpClientConnection.bind(socket, params); this.socketClientHttp = new BIOSocketClientHttp(defaultHttpClientConnection, this); ThreadPool.reserve().start((BIOSocketClientHttp) socketClientHttp); } return true; }
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;/*w ww . j av a 2 s.com*/ 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"); }