List of usage examples for java.net Socket close
public synchronized void close() throws IOException
From source file:org.mule.module.http.functional.listener.HttpListenerPersistentConnectionsTestCase.java
protected void assertConnectionClosesWithRequestConnectionCloseHeader(DynamicPort port, HttpVersion httpVersion) throws IOException, InterruptedException { Socket socket = new Socket("localhost", port.getNumber()); sendRequest(socket, httpVersion);//w w w . j a va 2s .c om assertResponse(getResponse(socket), true); sendRequest(socket, httpVersion); assertResponse(getResponse(socket), true); PrintWriter writer = new PrintWriter(socket.getOutputStream()); writer.println("GET / " + httpVersion); writer.println("Host: www.example.com"); writer.println("Connection: close"); writer.println(""); writer.flush(); assertResponse(getResponse(socket), true); sendRequest(socket, httpVersion); assertResponse(getResponse(socket), false); socket.close(); }
From source file:me.mast3rplan.phantombot.HTTPResponse.java
HTTPResponse(String address, String request) throws IOException { Socket sock = new Socket(address, 80); Writer output = new StringWriter(); IOUtils.write(request, sock.getOutputStream(), "utf-8"); IOUtils.copy(sock.getInputStream(), output); com.gmt2001.Console.out.println(output.toString()); Scanner scan = new Scanner(sock.getInputStream()); String errorLine = scan.nextLine(); for (String line = scan.nextLine(); !line.equals(""); line = scan.nextLine()) { String[] keyval = line.split(":", 2); if (keyval.length == 2) { values.put(keyval[0], keyval[1].trim()); } else {/*from w w w. ja v a 2 s. c o m*/ //? } } while (scan.hasNextLine()) { body += scan.nextLine(); } sock.close(); }
From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java
@Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { Args.notNull(host, "HTTP host"); Args.notNull(remoteAddress, "Remote address"); final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress);//from w ww . j a va 2 s .c om } try { if (connectTimeout > 0 && sock.getSoTimeout() == 0) { sock.setSoTimeout(connectTimeout); } LOGGER.debug("Connecting socket to {} with timeout {}", remoteAddress, connectTimeout); sock.connect(remoteAddress, connectTimeout); } catch (final IOException ex) { try { sock.close(); } catch (final IOException ignore) { } throw ex; } // Setup SSL layering if necessary if (sock instanceof SSLSocket) { final SSLSocket sslsock = (SSLSocket) sock; LOGGER.debug("Starting handshake"); sslsock.startHandshake(); verifyHostname(sslsock, host.getHostName()); return sock; } else { return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); } }
From source file:io.fabric8.kubernetes.api.KubernetesHelper.java
public static boolean isServiceSsl(String host, int port, boolean trustAllCerts) { try {/*from w w w .java 2 s.c o m*/ SSLSocketFactory sslsocketfactory = null; if (trustAllCerts) { sslsocketfactory = KubernetesFactory.TrustEverythingSSLTrustManager.getTrustingSSLSocketFactory(); } else { sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } Socket socket = sslsocketfactory.createSocket(); // Connect, with an explicit timeout value socket.connect(new InetSocketAddress(host, port), 1 * 1000); try { InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); // Write a test byte to get a reaction :) out.write(1); while (in.available() > 0) { System.out.print(in.read()); } return true; } finally { socket.close(); } } catch (SSLHandshakeException e) { LOG.error( "SSL handshake failed - this probably means that you need to trust the kubernetes root SSL certificate or set the environment variable " + KubernetesFactory.KUBERNETES_TRUST_ALL_CERIFICATES, e); } catch (SSLProtocolException e) { LOG.error("SSL protocol error", e); } catch (SSLKeyException e) { LOG.error("Bad SSL key", e); } catch (SSLPeerUnverifiedException e) { LOG.error("Could not verify server", e); } catch (SSLException e) { LOG.debug("Address does not appear to be SSL-enabled - falling back to http", e); } catch (IOException e) { LOG.debug("Failed to validate service", e); } return false; }
From source file:com.cloud.utils.crypt.EncryptionSecretKeyChecker.java
public void check(Properties dbProps) throws IOException { String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); s_logger.debug("Encryption Type: " + encryptionType); if (encryptionType == null || encryptionType.equals("none")) { return;/*www . j a v a2 s . c o m*/ } if (s_useEncryption) { s_logger.warn("Encryption already enabled, is check() called twice?"); return; } s_encryptor.setAlgorithm("PBEWithMD5AndDES"); String secretKey = null; SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); if (encryptionType.equals("file")) { InputStream is = this.getClass().getClassLoader().getResourceAsStream(s_keyFile); if (is == null) { is = this.getClass().getClassLoader().getResourceAsStream(s_altKeyFile); } if (is == null) { //This is means we are not able to load key file from the classpath. throw new CloudRuntimeException( s_keyFile + " File containing secret key not found in the classpath: "); } BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(is)); secretKey = in.readLine(); //Check for null or empty secret key } catch (IOException e) { throw new CloudRuntimeException("Error while reading secret key from: " + s_keyFile, e); } finally { IOUtils.closeQuietly(in); } if (secretKey == null || secretKey.isEmpty()) { throw new CloudRuntimeException("Secret key is null or empty in file " + s_keyFile); } } else if (encryptionType.equals("env")) { secretKey = System.getenv(s_envKey); if (secretKey == null || secretKey.isEmpty()) { throw new CloudRuntimeException("Environment variable " + s_envKey + " is not set or empty"); } } else if (encryptionType.equals("web")) { ServerSocket serverSocket = null; int port = 8097; try { serverSocket = new ServerSocket(port); } catch (IOException ioex) { throw new CloudRuntimeException("Error initializing secret key reciever", ioex); } s_logger.info("Waiting for admin to send secret key on port " + port); Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { throw new CloudRuntimeException("Accept failed on " + port); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; if ((inputLine = in.readLine()) != null) { secretKey = inputLine; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } else { throw new CloudRuntimeException("Invalid encryption type: " + encryptionType); } stringConfig.setPassword(secretKey); s_encryptor.setConfig(stringConfig); s_useEncryption = true; }
From source file:com.mtgi.analytics.test.AbstractPerformanceTestCase.java
private void runTest(ServerSocket listener, ProcessBuilder launcher, StatisticsMBean stats, byte[] jobData) throws IOException, InterruptedException { Process proc = launcher.start(); //connect stdout and stderr to parent process streams if (log.isDebugEnabled()) { new PipeThread(proc.getInputStream(), System.out).start(); new PipeThread(proc.getErrorStream(), System.err).start(); } else {//from w w w . java 2 s.c o m NullOutput sink = new NullOutput(); new PipeThread(proc.getInputStream(), sink).start(); new PipeThread(proc.getErrorStream(), sink).start(); } //wait for the incoming connection from the child process. Socket sock = listener.accept(); try { //connection established, send the job. OutputStream os = sock.getOutputStream(); os.write(jobData); os.flush(); //read measurements back. DataInputStream dis = new DataInputStream(sock.getInputStream()); for (long measure = dis.readLong(); measure >= 0; measure = dis.readLong()) stats.add(measure); //send ack byte to tell the child proc its ok to hang up. os.write(1); os.flush(); } finally { sock.close(); } assertEquals("Child process ended successfully", 0, proc.waitFor()); }
From source file:ch.cyberduck.core.ftp.FTPClient.java
public List<String> list(final FTPCmd command, final String pathname) throws IOException { this.pret(command, pathname); Socket socket = _openDataConnection_(command, pathname); BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream(), getControlEncoding())); ArrayList<String> results = new ArrayList<String>(); String line;/*from w w w .java 2 s . c o m*/ while ((line = reader.readLine()) != null) { _commandSupport_.fireReplyReceived(-1, line); results.add(line); } reader.close(); socket.close(); if (!this.completePendingCommand()) { throw new FTPException(this.getReplyCode(), this.getReplyString()); } return results; }
From source file:com.talis.platform.sequencing.zookeeper.ZkTestHelper.java
public boolean waitForServerUp(String hp, long timeout) { long start = System.currentTimeMillis(); String split[] = hp.split(":"); String host = split[0];/*from w w w .j a v a 2 s. co m*/ int port = Integer.parseInt(split[1]); while (true) { try { Socket sock = new Socket(host, port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes()); outstream.flush(); reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); String line = reader.readLine(); if (line != null && line.startsWith("Zookeeper version:")) { return true; } } finally { sock.close(); if (reader != null) { reader.close(); } } } catch (IOException e) { // ignore as this is expected LOG.info("server " + hp + " not up " + e); } if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } return false; }
From source file:com.adito.server.ServerLock.java
private void checkStatus() { Socket socket = null; try {/*from ww w . j a v a 2 s . co m*/ int timeout = 5000; // 5 seconds if (log.isInfoEnabled()) log.info("Connecting to " + bindAddress + ":" + port + " to see if a server is already running."); SocketAddress socketAddress = new InetSocketAddress(bindAddress, port); socket = new Socket(); socket.connect(socketAddress, timeout); locked = true; } catch (Exception e) { locked = false; } finally { if (socket != null) { try { socket.close(); } catch (Exception e) { } } } }
From source file:dualcontrol.CryptoClientDemo.java
private void call(Properties properties, MockableConsole console, String hostAddress, int port, byte[] data) throws Exception { Socket socket = SSLContexts.create(false, "cryptoclient.ssl", properties, console).getSocketFactory() .createSocket(hostAddress, port); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeShort(data.length);//from w ww. j ava2s .co m dos.write(data); dos.flush(); DataInputStream dis = new DataInputStream(socket.getInputStream()); byte[] ivBytes = new byte[dis.readShort()]; dis.readFully(ivBytes); byte[] bytes = new byte[dis.readShort()]; dis.readFully(bytes); if (new String(data).contains("DECRYPT")) { System.err.printf("INFO CryptoClientDemo decrypted %s\n", new String(bytes)); } else { System.out.printf("%s:%s\n", Base64.encodeBase64String(ivBytes), Base64.encodeBase64String(bytes)); } socket.close(); }