List of usage examples for java.net Socket connect
public void connect(SocketAddress endpoint) throws IOException
From source file:at.bitfire.davdroid.webdav.TlsSniSocketFactoryTest.java
public void testCreateLayeredSocket() { try {/*from ww w . j a v a2s .c o m*/ // connect plain socket first @Cleanup Socket plain = new Socket(); plain.connect(sampleTlsEndpoint); assertTrue(plain.isConnected()); // then create TLS socket on top of it and establish TLS Connection @Cleanup Socket socket = factory.createLayeredSocket(plain, sampleTlsEndpoint.getHostName(), sampleTlsEndpoint.getPort(), null); assertTrue(socket.isConnected()); } catch (IOException e) { Log.e(TAG, "I/O exception", e); fail(); } }
From source file:com.floragunn.searchguard.tools.SearchGuardAdmin.java
private static void main0(final String[] args) throws Exception { System.setProperty("sg.nowarn.client", "true"); final HelpFormatter formatter = new HelpFormatter(); Options options = new Options(); options.addOption("nhnv", "disable-host-name-verification", false, "Disable hostname verification"); options.addOption("nrhn", "disable-resolve-hostname", false, "Disable hostname beeing resolved"); options.addOption(Option.builder("ts").longOpt("truststore").hasArg().argName("file").required() .desc("Path to truststore (JKS/PKCS12 format)").build()); options.addOption(Option.builder("ks").longOpt("keystore").hasArg().argName("file").required() .desc("Path to keystore (JKS/PKCS12 format").build()); options.addOption(Option.builder("tst").longOpt("truststore-type").hasArg().argName("type") .desc("JKS or PKCS12, if not given use file ext. to dectect type").build()); options.addOption(Option.builder("kst").longOpt("keystore-type").hasArg().argName("type") .desc("JKS or PKCS12, if not given use file ext. to dectect type").build()); options.addOption(Option.builder("tspass").longOpt("truststore-password").hasArg().argName("password") .desc("Truststore password").build()); options.addOption(Option.builder("kspass").longOpt("keystore-password").hasArg().argName("password") .desc("Keystore password").build()); options.addOption(Option.builder("cd").longOpt("configdir").hasArg().argName("directory") .desc("Directory for config files").build()); options.addOption(Option.builder("h").longOpt("hostname").hasArg().argName("host") .desc("Elasticsearch host").build()); options.addOption(Option.builder("p").longOpt("port").hasArg().argName("port") .desc("Elasticsearch transport port (normally 9300)").build()); options.addOption(Option.builder("cn").longOpt("clustername").hasArg().argName("clustername") .desc("Clustername").build()); options.addOption("sniff", "enable-sniffing", false, "Enable client.transport.sniff"); options.addOption("icl", "ignore-clustername", false, "Ignore clustername"); options.addOption(Option.builder("r").longOpt("retrieve").desc("retrieve current config").build()); options.addOption(Option.builder("f").longOpt("file").hasArg().argName("file").desc("file").build()); options.addOption(//w ww .j a v a 2 s . c o m Option.builder("t").longOpt("type").hasArg().argName("file-type").desc("file-type").build()); options.addOption(Option.builder("tsalias").longOpt("truststore-alias").hasArg().argName("alias") .desc("Truststore alias").build()); options.addOption(Option.builder("ksalias").longOpt("keystore-alias").hasArg().argName("alias") .desc("Keystore alias").build()); options.addOption(Option.builder("ec").longOpt("enabled-ciphers").hasArg().argName("cipers") .desc("Comma separated list of TLS ciphers").build()); options.addOption(Option.builder("ep").longOpt("enabled-protocols").hasArg().argName("protocols") .desc("Comma separated list of TLS protocols").build()); //TODO mark as deprecated and replace it with "era" if "era" is mature enough options.addOption(Option.builder("us").longOpt("update_settings").hasArg().argName("number of replicas") .desc("update the number of replicas and reload configuration on all nodes and exit").build()); options.addOption(Option.builder("i").longOpt("index").hasArg().argName("indexname") .desc("The index Searchguard uses to store its configs in").build()); options.addOption(Option.builder("era").longOpt("enable-replica-autoexpand") .desc("enable replica auto expand and exit").build()); options.addOption(Option.builder("dra").longOpt("disable-replica-autoexpand") .desc("disable replica auto expand and exit").build()); options.addOption( Option.builder("rl").longOpt("reload").desc("reload configuration on all nodes and exit").build()); options.addOption( Option.builder("ff").longOpt("fail-fast").desc("fail-fast if something goes wrong").build()); options.addOption( Option.builder("dg").longOpt("diagnose").desc("Log diagnostic trace into a file").build()); options.addOption(Option.builder("dci").longOpt("delete-config-index") .desc("Delete 'searchguard' config index and exit.").build()); options.addOption(Option.builder("esa").longOpt("enable-shard-allocation") .desc("Enable all shard allocation and exit.").build()); String hostname = "localhost"; int port = 9300; String kspass = System.getenv(SG_KS_PASS) != null ? System.getenv(SG_KS_PASS) : "changeit"; String tspass = System.getenv(SG_TS_PASS) != null ? System.getenv(SG_TS_PASS) : kspass; String cd = "."; String ks; String ts; String kst = null; String tst = null; boolean nhnv = false; boolean nrhn = false; boolean sniff = false; boolean icl = false; String clustername = "elasticsearch"; String file = null; String type = null; boolean retrieve = false; String ksAlias = null; String tsAlias = null; String[] enabledProtocols = new String[0]; String[] enabledCiphers = new String[0]; Integer updateSettings = null; String index = ConfigConstants.SG_DEFAULT_CONFIG_INDEX; Boolean replicaAutoExpand = null; boolean reload = false; boolean failFast = false; boolean diagnose = false; boolean deleteConfigIndex = false; boolean enableShardAllocation = false; CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, args); hostname = line.getOptionValue("h", hostname); port = Integer.parseInt(line.getOptionValue("p", String.valueOf(port))); kspass = line.getOptionValue("kspass", kspass); //TODO null? //when no passwd is set tspass = line.getOptionValue("tspass", tspass); //TODO null? //when no passwd is set cd = line.getOptionValue("cd", cd); if (!cd.endsWith(File.separator)) { cd += File.separator; } ks = line.getOptionValue("ks"); ts = line.getOptionValue("ts"); kst = line.getOptionValue("kst", kst); tst = line.getOptionValue("tst", tst); nhnv = line.hasOption("nhnv"); nrhn = line.hasOption("nrhn"); clustername = line.getOptionValue("cn", clustername); sniff = line.hasOption("sniff"); icl = line.hasOption("icl"); file = line.getOptionValue("f", file); type = line.getOptionValue("t", type); retrieve = line.hasOption("r"); ksAlias = line.getOptionValue("ksalias", ksAlias); tsAlias = line.getOptionValue("tsalias", tsAlias); index = line.getOptionValue("i", index); String enabledCiphersString = line.getOptionValue("ec", null); String enabledProtocolsString = line.getOptionValue("ep", null); if (enabledCiphersString != null) { enabledCiphers = enabledCiphersString.split(","); } if (enabledProtocolsString != null) { enabledProtocols = enabledProtocolsString.split(","); } updateSettings = line.hasOption("us") ? Integer.parseInt(line.getOptionValue("us")) : null; reload = line.hasOption("rl"); if (line.hasOption("era")) { replicaAutoExpand = true; } if (line.hasOption("dra")) { replicaAutoExpand = false; } failFast = line.hasOption("ff"); diagnose = line.hasOption("dg"); deleteConfigIndex = line.hasOption("dci"); enableShardAllocation = line.hasOption("esa"); } catch (ParseException exp) { System.err.println("ERR: Parsing failed. Reason: " + exp.getMessage()); formatter.printHelp("sgadmin.sh", options, true); return; } if (port < 9300) { System.out.println("WARNING: Seems you want connect to the a HTTP port." + System.lineSeparator() + " sgadmin connect through the transport port which is normally 9300."); } System.out.print("Will connect to " + hostname + ":" + port); Socket socket = new Socket(); try { socket.connect(new InetSocketAddress(hostname, port)); } catch (java.net.ConnectException ex) { System.out.println(); System.out.println( "ERR: Seems there is no elasticsearch running on " + hostname + ":" + port + " - Will exit"); System.exit(-1); } finally { try { socket.close(); } catch (Exception e) { //ignore } } System.out.println(" ... done"); final Settings.Builder settingsBuilder = Settings.builder().put("path.home", ".").put("path.conf", ".") .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, ks) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, ts) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_PASSWORD, kspass) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_PASSWORD, tspass) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENFORCE_HOSTNAME_VERIFICATION, !nhnv) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENFORCE_HOSTNAME_VERIFICATION_RESOLVE_HOST_NAME, !nrhn) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED, true) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_TYPE, kst == null ? (ks.endsWith(".jks") ? "JKS" : "PKCS12") : kst) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_TYPE, tst == null ? (ts.endsWith(".jks") ? "JKS" : "PKCS12") : tst) .putArray(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED_CIPHERS, enabledCiphers) .putArray(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLED_PROTOCOLS, enabledProtocols) .put("cluster.name", clustername).put("client.transport.ignore_cluster_name", icl) .put("client.transport.sniff", sniff); if (ksAlias != null) { settingsBuilder.put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS, ksAlias); } if (tsAlias != null) { settingsBuilder.put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_ALIAS, tsAlias); } Settings settings = settingsBuilder.build(); try (TransportClient tc = TransportClient.builder().settings(settings).addPlugin(SearchGuardSSLPlugin.class) .addPlugin(SearchGuardPlugin.class) //needed for config update action only .build() .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(hostname, port)))) { if (updateSettings != null) { Settings indexSettings = Settings.builder().put("index.number_of_replicas", updateSettings).build(); tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest( new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" })) .actionGet(); final UpdateSettingsResponse response = tc.admin().indices() .updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet(); System.out.println("Reload config on all nodes"); System.out.println("Update number of replicas to " + (updateSettings) + " with result: " + response.isAcknowledged()); System.exit(response.isAcknowledged() ? 0 : -1); } if (reload) { tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest( new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" })) .actionGet(); System.out.println("Reload config on all nodes"); System.exit(0); } if (replicaAutoExpand != null) { Settings indexSettings = Settings.builder() .put("index.auto_expand_replicas", replicaAutoExpand ? "0-all" : "false").build(); tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest( new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" })) .actionGet(); final UpdateSettingsResponse response = tc.admin().indices() .updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet(); System.out.println("Reload config on all nodes"); System.out.println("Auto-expand replicas " + (replicaAutoExpand ? "enabled" : "disabled")); System.exit(response.isAcknowledged() ? 0 : -1); } if (enableShardAllocation) { final boolean successful = tc.admin().cluster() .updateSettings(new ClusterUpdateSettingsRequest() .transientSettings(ENABLE_ALL_ALLOCATIONS_SETTINGS) .persistentSettings(ENABLE_ALL_ALLOCATIONS_SETTINGS)) .actionGet().isAcknowledged(); if (successful) { System.out.println("Persistent and transient shard allocation enabled"); } else { System.out.println("ERR: Unable to enable shard allocation"); } System.exit(successful ? 0 : -1); } if (failFast) { System.out.println("Failfast is activated"); } if (diagnose) { generateDiagnoseTrace(tc); } System.out.println( "Contacting elasticsearch cluster '" + clustername + "' and wait for YELLOW clusterstate ..."); ClusterHealthResponse chr = null; while (chr == null) { try { chr = tc.admin().cluster().health( new ClusterHealthRequest().timeout(TimeValue.timeValueMinutes(5)).waitForYellowStatus()) .actionGet(); } catch (Exception e) { if (!failFast) { System.out.println("Cannot retrieve cluster state due to: " + e.getMessage() + ". This is not an error, will keep on trying ..."); System.out.println( " * Try running sgadmin.sh with -icl and -nhnv (If thats works you need to check your clustername as well as hostnames in your SSL certificates)"); System.out.println( " * If this is not working, try running sgadmin.sh with --diagnose and see diagnose trace log file)"); } else { System.out.println("ERR: Cannot retrieve cluster state due to: " + e.getMessage() + "."); System.out.println( " * Try running sgadmin.sh with -icl and -nhnv (If thats works you need to check your clustername as well as hostnames in your SSL certificates)"); System.out.println( " * If this is not working, try running sgadmin.sh with --diagnose and see diagnose trace log file)"); System.exit(-1); } Thread.sleep(3000); continue; } } final boolean timedOut = chr.isTimedOut(); if (timedOut) { System.out.println("ERR: Timed out while waiting for a green or yellow cluster state."); System.out.println( " * Try running sgadmin.sh with -icl and -nhnv (If thats works you need to check your clustername as well as hostnames in your SSL certificates)"); System.exit(-1); } System.out.println("Clustername: " + chr.getClusterName()); System.out.println("Clusterstate: " + chr.getStatus()); System.out.println("Number of nodes: " + chr.getNumberOfNodes()); System.out.println("Number of data nodes: " + chr.getNumberOfDataNodes()); final boolean indexExists = tc.admin().indices().exists(new IndicesExistsRequest(index)).actionGet() .isExists(); final NodesInfoResponse nodesInfo = tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet(); if (deleteConfigIndex) { boolean success = true; if (indexExists) { success = tc.admin().indices().delete(new DeleteIndexRequest(index)).actionGet() .isAcknowledged(); System.out.print("Deleted index '" + index + "'"); } else { System.out.print("No index '" + index + "' exists, so no need to delete it"); } System.exit(success ? 0 : -1); } if (!indexExists) { System.out.print(index + " index does not exists, attempt to create it ... "); int replicas = chr.getNumberOfDataNodes() - 1; final boolean indexCreated = tc.admin().indices().create(new CreateIndexRequest(index) // .mapping("config", source) // .settings(settings) //TODO "index.auto_expand_replicas", "0-all" .settings("index.number_of_shards", 1, "index.number_of_replicas", replicas)).actionGet() .isAcknowledged(); if (indexCreated) { System.out.println("done (with " + replicas + " replicas, auto expand replicas is off)"); } else { System.out.println("failed!"); System.out.println("FAIL: Unable to create the " + index + " index. See elasticsearch logs for more details"); System.exit(-1); } } else { System.out.println(index + " index already exists, so we do not need to create one."); try { ClusterHealthResponse chrsg = tc.admin().cluster().health(new ClusterHealthRequest(index)) .actionGet(); if (chrsg.isTimedOut()) { System.out.println("ERR: Timed out while waiting for " + index + " index state."); } if (chrsg.getStatus() == ClusterHealthStatus.RED) { System.out.println("ERR: " + index + " index state is RED."); } if (chrsg.getStatus() == ClusterHealthStatus.YELLOW) { System.out.println( "INFO: " + index + " index state is YELLOW, it seems you miss some replicas"); } } catch (Exception e) { if (!failFast) { System.out.println("Cannot retrieve " + index + " index state state due to " + e.getMessage() + ". This is not an error, will keep on trying ..."); } else { System.out.println("ERR: Cannot retrieve " + index + " index state state due to " + e.getMessage() + "."); System.exit(-1); } } } if (retrieve) { String date = DATE_FORMAT.format(new Date()); boolean success = retrieveFile(tc, cd + "sg_config_" + date + ".yml", index, "config"); success = success & retrieveFile(tc, cd + "sg_roles_" + date + ".yml", index, "roles"); success = success & retrieveFile(tc, cd + "sg_roles_mapping_" + date + ".yml", index, "rolesmapping"); success = success & retrieveFile(tc, cd + "sg_internal_users_" + date + ".yml", index, "internalusers"); success = success & retrieveFile(tc, cd + "sg_action_groups_" + date + ".yml", index, "actiongroups"); System.exit(success ? 0 : -1); } boolean isCdAbs = new File(cd).isAbsolute(); System.out.println("Populate config from " + (isCdAbs ? cd : new File(".", cd).getCanonicalPath())); if (file != null) { if (type == null) { System.out.println("ERR: type missing"); System.exit(-1); } if (!Arrays .asList(new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }) .contains(type)) { System.out.println("ERR: Invalid type '" + type + "'"); System.exit(-1); } boolean success = uploadFile(tc, file, index, type); System.exit(success ? 0 : -1); } boolean success = uploadFile(tc, cd + "sg_config.yml", index, "config"); success = success & uploadFile(tc, cd + "sg_roles.yml", index, "roles"); success = success & uploadFile(tc, cd + "sg_roles_mapping.yml", index, "rolesmapping"); success = success & uploadFile(tc, cd + "sg_internal_users.yml", index, "internalusers"); success = success & uploadFile(tc, cd + "sg_action_groups.yml", index, "actiongroups"); if (failFast && !success) { System.out.println("ERR: cannot upload configuration, see errors above"); System.exit(-1); } ConfigUpdateResponse cur = tc .execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest( new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" })) .actionGet(); success = success & checkConfigUpdateResponse(cur, nodesInfo, 5); System.out.println("Done with " + (success ? "success" : "failures")); System.exit(success ? 0 : -1); } // TODO audit changes to searchguard index }
From source file:gridool.communication.transport.tcp.GridNonBlockingClient.java
public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException { final SocketChannel channel; try {/*from w w w . j a v a 2 s. com*/ channel = SocketChannel.open(); channel.configureBlocking(false); } catch (IOException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException(e); } final Socket socket = channel.socket(); try { socket.connect(sockAddr); // wait for connect succeeds while (!channel.finishConnect()) { try { Thread.sleep(1000L); } catch (InterruptedException e) { ; } } } catch (IOException e) { IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException(e); } final ByteBuffer buf = toBuffer(msg); if (LOG.isDebugEnabled()) { LOG.debug("Sending a GridCommunicationMessage [" + msg.getMessageId() + " (" + buf.remaining() + " bytes)] to a node [" + sockAddr + "] using a channel [" + channel + ']'); } final int written; try { written = NIOUtils.countingWriteFully(channel, buf); NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN) } catch (IOException ioe) { final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr + ']'; LOG.error(errmsg, ioe); throw new GridException(errmsg, ioe); } catch (Throwable e) { LOG.fatal(e.getMessage(), e); throw new GridException("Unexpected exception was caused", e); } finally { NetUtils.closeQuietly(socket); } if (LOG.isDebugEnabled()) { LOG.debug("Succeeded to send a GridCommunicationMessage (" + written + " bytes) to host [" + sockAddr + "]"); } }
From source file:com.flipkart.phantom.thrift.impl.proxy.SocketObjectFactory.java
/** * Interface method implementation. Creates and returns a new {@link java.net.Socket} * @see org.apache.commons.pool.PoolableObjectFactory#makeObject() *///from w w w. j a va 2s .c o m public Socket makeObject() throws Exception { Socket socket = new Socket(); socket.setSoTimeout(this.getThriftProxy().getThriftTimeoutMillis()); socket.connect(new InetSocketAddress(this.getThriftProxy().getThriftServer(), this.getThriftProxy().getThriftPort())); LOGGER.info("Creating a new socket for server : {} at port : {}", this.getThriftProxy().getThriftServer(), this.getThriftProxy().getThriftPort()); return socket; }
From source file:org.conqat.engine.bugzilla.lib.SimpleSSLSocketFactory.java
/** {@inheritDoc} */ @Override/*w w w. j a v a 2 s . co m*/ public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException, UnknownHostException { // work-around for bug in Java 7 (see // http://stackoverflow.com/questions/7615645/ssl-handshake-alert-unrecognized-name-error-since-upgrade-to-java-1-7-0 // and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7127374 for // details) Socket socket = sc.getSocketFactory().createSocket(); socket.bind(new InetSocketAddress(localAddress, localPort)); socket.connect(new InetSocketAddress(host, port)); return socket; }
From source file:com.sun.faban.driver.transport.hc3.AboveTimedSSLSocketFactory.java
public Socket createSocket(String host, int port) throws IOException { Socket socket = new TimedSocketWrapper(sslFactory.createSocket()); InetSocketAddress endpoint = new InetSocketAddress(host, port); socket.connect(endpoint); return socket; }
From source file:org.apache.ftpserver.socketfactory.FtpSocketFactoryTest.java
private void testCreateServerSocket(final FtpSocketFactory ftpSocketFactory, final int port) throws Exception, IOException { boolean freePort = false; try {/*from www. ja v a 2s . c o m*/ final ServerSocket testSocket = new ServerSocket(port, 100); freePort = testSocket.isBound(); testSocket.close(); } catch (Exception exc) { // ok freePort = true; } if (freePort) { new Thread() { public void run() { synchronized (this) { try { this.wait(1000); } catch (InterruptedException e) { e.printStackTrace(); fail(e.toString()); } } try { Socket socket = new Socket(); socket.connect(new InetSocketAddress("localhost", port)); socket.getInputStream(); socket.getOutputStream(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); fail(e.toString()); } catch (IOException e) { e.printStackTrace(); fail(e.toString()); } } }.start(); ServerSocket serverSocket = ftpSocketFactory.createServerSocket(); assertNotNull(serverSocket); serverSocket.accept(); } }
From source file:com.cloudant.tests.util.SimpleHttpServer.java
/** * Called automatically by after when used as a JUnit ExternalResource. * Stop is exposed here for manual use.//from w w w . jav a2s.com */ public void stop() { if (!finished.getAndSet(true)) { //if the server hadn't already finished then connect to it here to unblock the last //socket.accept() call and allow the server to terminate cleanly Socket socket = new Socket(); try { socket.connect(getSocketAddress()); } catch (Exception e) { log.log(Level.SEVERE, "Exception when shutting down ", e); } finally { IOUtils.closeQuietly(socket); } } IOUtils.closeQuietly(serverSocket); try { //wait for the server thread to finish serverThread.join(); } catch (InterruptedException e) { log.log(Level.SEVERE, SimpleHttpServer.class.getName() + " interrupted", e); } }
From source file:io.undertow.server.handlers.ReceiverTestCase.java
@Test public void testAsyncReceiveWholeBytesFailed() throws Exception { EXCEPTIONS.clear();//from ww w . jav a 2 s . c om Socket socket = new Socket(); socket.connect(DefaultServer.getDefaultServerAddress()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10000; ++i) { sb.append("hello world\r\n"); } //send a large request that is too small, then kill the socket String request = "POST /fullbytes HTTP/1.1\r\nHost:localhost\r\nContent-Length:" + sb.length() + 100 + "\r\n\r\n" + sb.toString(); OutputStream outputStream = socket.getOutputStream(); outputStream.write(request.getBytes("US-ASCII")); socket.getInputStream().close(); outputStream.close(); IOException e = EXCEPTIONS.poll(2, TimeUnit.SECONDS); Assert.assertNotNull(e); }
From source file:gobblin.tunnel.ConnectProxyServer.java
@Override void handleClientSocket(Socket clientSocket) throws IOException { final InputStream clientToProxyIn = clientSocket.getInputStream(); BufferedReader clientToProxyReader = new BufferedReader(new InputStreamReader(clientToProxyIn)); final OutputStream clientToProxyOut = clientSocket.getOutputStream(); String line = clientToProxyReader.readLine(); String connectRequest = ""; while (line != null && isServerRunning()) { connectRequest += line + "\r\n"; if (connectRequest.endsWith("\r\n\r\n")) { break; }//from w w w .j a va 2 s . c o m line = clientToProxyReader.readLine(); } // connect to given host:port Matcher matcher = hostPortPattern.matcher(connectRequest); if (!matcher.find()) { try { sendConnectResponse("400 Bad Request", clientToProxyOut, null, 0); } finally { clientSocket.close(); stopServer(); } return; } String host = matcher.group(1); int port = Integer.decode(matcher.group(2)); // connect to server Socket serverSocket = new Socket(); try { serverSocket.connect(new InetSocketAddress(host, port)); addSocket(serverSocket); byte[] initialServerResponse = null; int nbytes = 0; if (mixServerAndProxyResponse) { // we want to mix the initial server response with the 200 OK initialServerResponse = new byte[64]; nbytes = serverSocket.getInputStream().read(initialServerResponse); } sendConnectResponse("200 OK", clientToProxyOut, initialServerResponse, nbytes); } catch (IOException e) { try { sendConnectResponse("404 Not Found", clientToProxyOut, null, 0); } finally { clientSocket.close(); stopServer(); } return; } final InputStream proxyToServerIn = serverSocket.getInputStream(); final OutputStream proxyToServerOut = serverSocket.getOutputStream(); _threads.add(new EasyThread() { @Override void runQuietly() throws Exception { try { IOUtils.copy(clientToProxyIn, proxyToServerOut); } catch (IOException e) { LOG.warn("Exception " + e.getMessage() + " on " + getServerSocketPort()); } } }.startThread()); try { if (nBytesToCloseSocketAfter > 0) { // Simulate proxy abruptly closing connection int leftToRead = nBytesToCloseSocketAfter; byte[] buffer = new byte[leftToRead + 256]; while (true) { int numRead = proxyToServerIn.read(buffer, 0, leftToRead); if (numRead < 0) { break; } clientToProxyOut.write(buffer, 0, numRead); clientToProxyOut.flush(); leftToRead -= numRead; if (leftToRead <= 0) { LOG.warn("Cutting connection after " + nBytesToCloseSocketAfter + " bytes"); break; } } } else { IOUtils.copy(proxyToServerIn, clientToProxyOut); } } catch (IOException e) { LOG.warn("Exception " + e.getMessage() + " on " + getServerSocketPort()); } clientSocket.close(); serverSocket.close(); }