List of usage examples for java.net ServerSocket setReuseAddress
public void setReuseAddress(boolean on) throws SocketException
From source file:org.structr.util.StructrLicenseVerifier.java
private void run() { try {/*from ww w.j a v a 2 s . c o m*/ logger.info("Listening on port {}", StructrLicenseManager.ServerPort); final ServerSocket serverSocket = new ServerSocket(StructrLicenseManager.ServerPort); serverSocket.setReuseAddress(true); // validation loop while (true) { try (final Socket socket = serverSocket.accept()) { logger.info("##### New connection from {}", socket.getInetAddress().getHostAddress()); final InputStream is = socket.getInputStream(); final int bufSize = 4096; socket.setSoTimeout(2000); // decrypt AES stream key using RSA block cipher final byte[] sessionKey = blockCipher.doFinal(IOUtils.readFully(is, 256)); final byte[] ivSpec = blockCipher.doFinal(IOUtils.readFully(is, 256)); final byte[] buf = new byte[bufSize]; int count = 0; // initialize cipher using stream key streamCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sessionKey, "AES"), new IvParameterSpec(ivSpec)); // we want to be able to control the number of bytes AND the timeout // of the underlying socket, so that we read the available amount of // data until the socket times out or we have read all the data. try { count = is.read(buf, 0, bufSize); } catch (IOException ioex) { } final byte[] decrypted = streamCipher.doFinal(buf, 0, count); final String data = new String(decrypted, "utf-8"); // transform decrypted data into a Map<String, String> final List<Pair> pairs = split(data).stream().map(StructrLicenseVerifier::keyValue) .collect(Collectors.toList()); final Map<String, String> map = pairs.stream().filter(Objects::nonNull) .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); // validate data against customer database if (isValid(map)) { // send signatur of name field back to client final String name = (String) map.get(StructrLicenseManager.NameKey); final byte[] response = name.getBytes("utf-8"); // respond with the signature of the data sent to us socket.getOutputStream().write(sign(response)); socket.getOutputStream().flush(); } else { logger.info("License verification failed."); } socket.getOutputStream().close(); } catch (Throwable t) { logger.warn("Unable to verify license: {}", t.getMessage()); } } } catch (Throwable t) { logger.warn("Unable to verify license: {}", t.getMessage()); } }
From source file:com.adeptj.runtime.server.Server.java
private boolean isPortAvailable(int port) { boolean portAvailable = false; ServerSocket socket = null; try (ServerSocketChannel socketChannel = ServerSocketChannel.open()) { socket = socketChannel.socket(); socket.setReuseAddress(true); socket.bind(new InetSocketAddress(port)); portAvailable = true;/*from www . j a v a 2 s.c o m*/ } catch (BindException ex) { LOGGER.error("BindException while acquiring port: [{}], cause:", port, ex); } catch (IOException ex) { LOGGER.error("IOException while acquiring port: [{}], cause:", port, ex); } finally { if (socket != null) { try { socket.close(); } catch (IOException ex) { LOGGER.error("IOException while closing socket!!", ex); } } } return portAvailable; }
From source file:org.vaadin.testbenchsauce.BaseTestBenchTestCase.java
private static int findFreePort() { ServerSocket socket = null; try {// w w w . j a v a 2 s . c o m socket = new ServerSocket(0); socket.setReuseAddress(true); int port = socket.getLocalPort(); try { socket.close(); } catch (IOException e) { // Ignore IOException on close() } return port; } catch (IOException ignored) { } finally { if (socket != null) { try { socket.close(); } catch (IOException ignored) { } } } throw new IllegalStateException("Could not find a free TCP/IP port to start embedded Jetty HTTP Server on"); }
From source file:org.apache.camel.itest.http.HttpTestServer.java
/** * Starts this test server./*w ww . j a v a 2 s . co m*/ */ public void start() throws Exception { if (servicedSocket != null) { throw new IllegalStateException(this.toString() + " already running"); } ServerSocket ssock; if (sslcontext != null) { SSLServerSocketFactory sf = sslcontext.getServerSocketFactory(); ssock = sf.createServerSocket(); } else { ssock = new ServerSocket(); } ssock.setReuseAddress(true); // probably pointless for port '0' ssock.bind(TEST_SERVER_ADDR); servicedSocket = ssock; listenerThread = new ListenerThread(); listenerThread.setDaemon(false); listenerThread.start(); }
From source file:org.apache.hadoop.hdfs.fsshellservice.FsShellServiceImpl.java
private void initThriftServer(int port, int maxQueue) { // Setup the Thrift server LOG.info("Setting up Thrift server listening port " + port); TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(); TTransportFactory transportFactory = new TFramedTransport.Factory(); TServerTransport serverTransport;/* www. j a va 2 s . c om*/ FsShellService.Processor<FsShellService.Iface> processor = new FsShellService.Processor<FsShellService.Iface>( this); ServerSocket serverSocket_; try { // Make server socket. Use loop-back address to only serve requests // from local clients, in order to prevent ambiguity for commands // of copyFromLocal() and copyToLocal() serverSocket_ = new ServerSocket(port, maxQueue, InetAddress.getAllByName(null)[0]); // Prevent 2MSL delay problem on server restarts serverSocket_.setReuseAddress(true); } catch (IOException ioe) { LOG.error("Could not create ServerSocket on local address ", ioe); return; } serverTransport = new TServerSocket(serverSocket_, clientTimeout); TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport); serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory); tserver = new TThreadPoolServer(serverArgs); }
From source file:org.apache.http.localserver.LocalTestServer.java
/** * Starts this test server.//from w w w. j a v a2 s .c om * Use {@link #getServicePort getServicePort} * to obtain the port number afterwards. */ public void start() throws Exception { if (servicedSocket != null) throw new IllegalStateException(this.toString() + " already running"); ServerSocket ssock; if (sslcontext != null) { SSLServerSocketFactory sf = sslcontext.getServerSocketFactory(); ssock = sf.createServerSocket(); } else { ssock = new ServerSocket(); } ssock.setReuseAddress(true); // probably pointless for port '0' ssock.bind(TEST_SERVER_ADDR); servicedSocket = ssock; listenerThread = new Thread(new RequestListener()); listenerThread.setDaemon(false); listenerThread.start(); }
From source file:de.kapsi.net.daap.nio.DaapServerNIO.java
/** * Binds this server to the SocketAddress supplied by DaapConfig * /*from w w w . j a va2 s . co m*/ * @throws IOException */ public void bind() throws IOException { SocketAddress bindAddr = config.getInetSocketAddress(); int backlog = config.getBacklog(); try { ssc = ServerSocketChannel.open(); ServerSocket socket = ssc.socket(); // BugID: 4546610 // On Win2k, Mac OS X, XYZ it is possible to bind // the same address without rising a SocketException // (the Documentation lies) socket.setReuseAddress(false); try { socket.bind(bindAddr, backlog); } catch (SocketException err) { throw new BindException(err.getMessage()); } ssc.configureBlocking(false); if (LOG.isInfoEnabled()) { LOG.info("DaapServerNIO bound to " + bindAddr); } streams = new HashSet(); connections = new HashSet(); sessionIds = new HashSet(); } catch (IOException err) { close(); throw err; } }
From source file:com.addthis.hydra.task.output.tree.TreeMapper.java
private void _init(TaskRunConfig runConfig) throws Exception { config = runConfig;/*ww w.jav a 2 s.c o m*/ mapstats = new TreeMapperStats(log); resolve(); if (nodeCache != null) TreeCommonParameters.setDefaultCleanQueueSize(nodeCache); if (trashInterval != null) TreeCommonParameters.setDefaultTrashInterval(trashInterval); if (trashTimeLimit != null) TreeCommonParameters.setDefaultTrashTimeLimit(trashTimeLimit); if (storage != null) { if (storage.maxCacheSize != null) TreeCommonParameters.setDefaultMaxCacheSize(storage.maxCacheSize); if (storage.maxCacheMem != null) TreeCommonParameters.setDefaultMaxCacheMem(storage.maxCacheMem); if (storage.maxPageSize != null) TreeCommonParameters.setDefaultMaxPageSize(storage.maxCacheSize); if (storage.maxPageMem != null) TreeCommonParameters.setDefaultMaxPageMem(storage.maxPageMem); if (storage.memSample != null) TreeCommonParameters.setDefaultMemSample(storage.memSample); } if (Strings.isEmpty(localhost)) { localhost = InetAddress.getLocalHost().getHostAddress(); } log.info("[init] java=" + System.getProperty("java.vm.version") + " query=" + enableQuery + " http=" + enableHttp + " jmx=" + enableJmx + " live=" + live); log.info("[init] host=" + localhost + " port=" + port + " target=" + root + " job=" + config.jobId); Path treePath = Paths.get(runConfig.dir, "data"); tree = new ConcurrentTree(Files.initDirectory(treePath.toFile())); bench = new Bench(EnumSet.allOf(BENCH.class), 1000); if (enableHttp) { jetty = new Server(port > 0 ? port++ : 0); jetty.start(); int httpPort = jetty.getConnectors()[0].getLocalPort(); log.info("[init.http] http://" + localhost + ":" + httpPort + "/"); Files.write(new File("job.port"), Bytes.toBytes(Integer.toString(httpPort)), false); } if (enableJmx) { int queryPort = 0; jmxname = new ObjectName("com.addthis.hydra:type=Hydra,node=" + queryPort); ManagementFactory.getPlatformMBeanServer().registerMBean(mapstats, jmxname); ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(port > 0 ? new InetSocketAddress(port++) : null); int jmxport = ss.getLocalPort(); ss.close(); if (jmxport == -1) { log.warn("[init.jmx] failed to get a port"); } else { try { jmxremote = new MBeanRemotingSupport(jmxport); jmxremote.start(); log.info("[init.jmx] port=" + jmxport); } catch (Exception e) { log.warn("[init.jmx] err=" + e); } } } if (config.jobId != null && live && livePort > -1) { QueryEngine liveQueryEngine = new QueryEngine(tree); connectToMesh(treePath.toFile(), runConfig.jobId, liveQueryEngine); } startTime = System.currentTimeMillis(); if (pre != null) { log.warn("pre-chain: " + pre); processBundle(new KVBundle(), pre); } }
From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java
/** * Checks if port is available on given address. * * @param port port to check for availability * @throws ConfigurationException Throws an exception if address is unavailable. * @since 5.5/* w ww . ja v a 2 s. co m*/ */ public static void checkPortAvailable(InetAddress address, int port) throws ConfigurationException { if ((port == 0) || (port == -1)) { log.warn("Port is set to " + Integer.toString(port) + " - assuming it is disabled - skipping availability check"); return; } if (port < MIN_PORT || port > MAX_PORT) { throw new IllegalArgumentException("Invalid port: " + port); } ServerSocket socketTCP = null; // DatagramSocket socketUDP = null; try { log.debug("Checking availability of port " + port + " on address " + address); socketTCP = new ServerSocket(port, 0, address); socketTCP.setReuseAddress(true); // socketUDP = new DatagramSocket(port, address); // socketUDP.setReuseAddress(true); // return true; } catch (IOException e) { throw new ConfigurationException(e.getMessage() + ": " + address + ":" + port, e); } finally { // if (socketUDP != null) { // socketUDP.close(); // } if (socketTCP != null) { try { socketTCP.close(); } catch (IOException e) { // Do not throw } } } }
From source file:org.apache.geode.internal.net.SocketCreator.java
private ServerSocket createServerSocket(int nport, int backlog, InetAddress bindAddr, int socketBufferSize, boolean sslConnection) throws IOException { printConfig();/* w w w . j a v a 2 s .c o m*/ if (sslConnection) { if (this.sslContext == null) { throw new GemFireConfigException("SSL not configured correctly, Please look at previous error"); } ServerSocketFactory ssf = this.sslContext.getServerSocketFactory(); SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket(); serverSocket.setReuseAddress(true); // If necessary, set the receive buffer size before binding the socket so // that large buffers will be allocated on accepted sockets (see // java.net.ServerSocket.setReceiverBufferSize javadocs) if (socketBufferSize != -1) { serverSocket.setReceiveBufferSize(socketBufferSize); } serverSocket.bind(new InetSocketAddress(bindAddr, nport), backlog); finishServerSocket(serverSocket); return serverSocket; } else { // log.info("Opening server socket on " + nport, new Exception("SocketCreation")); ServerSocket result = new ServerSocket(); result.setReuseAddress(true); // If necessary, set the receive buffer size before binding the socket so // that large buffers will be allocated on accepted sockets (see // java.net.ServerSocket.setReceiverBufferSize javadocs) if (socketBufferSize != -1) { result.setReceiveBufferSize(socketBufferSize); } try { result.bind(new InetSocketAddress(bindAddr, nport), backlog); } catch (BindException e) { BindException throwMe = new BindException( LocalizedStrings.SocketCreator_FAILED_TO_CREATE_SERVER_SOCKET_ON_0_1 .toLocalizedString(new Object[] { bindAddr, Integer.valueOf(nport) })); throwMe.initCause(e); throw throwMe; } return result; } }