List of usage examples for java.net InetSocketAddress getAddress
public final InetAddress getAddress()
From source file:org.openhab.binding.keba.handler.KeContactP20Handler.java
protected ByteBuffer onReadable(DatagramChannel theChannel, int bufferSize, InetAddress permittedClientAddress) { lock.lock();// w w w .j a va 2s. c o m try { SelectionKey theSelectionKey = theChannel.keyFor(selector); if (theSelectionKey != null) { synchronized (selector) { try { selector.selectNow(); } catch (IOException e) { logger.error("An exception occurred while selecting: {}", e.getMessage()); } } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); it.remove(); if (selKey.isValid() && selKey.isReadable() && selKey == theSelectionKey) { ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize); int numberBytesRead = 0; boolean error = false; if (selKey == listenerKey) { try { InetSocketAddress clientAddress = (InetSocketAddress) theChannel .receive(readBuffer); if (clientAddress.getAddress().equals(permittedClientAddress)) { logger.debug("Received {} on the listener port from {}", new String(readBuffer.array()), clientAddress); numberBytesRead = readBuffer.position(); } else { logger.warn( "Received data from '{}' which is not the permitted remote address '{}'", clientAddress, permittedClientAddress); return null; } } catch (Exception e) { logger.error( "An exception occurred while receiving data on the listener port: '{}'", e.getMessage()); error = true; } } else { try { numberBytesRead = theChannel.read(readBuffer); } catch (NotYetConnectedException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "The remote host is not yet connected"); error = true; } catch (PortUnreachableException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The remote host is probably not a KEBA EV Charging station"); error = true; } catch (IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "An IO exception occurred"); error = true; } } if (numberBytesRead == -1) { error = true; } if (error) { logger.debug("Disconnecting '{}' because of a socket error", getThing().getUID().toString()); try { theChannel.close(); } catch (IOException e) { logger.error("An exception occurred while closing the channel '{}': {}", datagramChannel, e.getMessage()); } onConnectionLost(); } else { readBuffer.flip(); return readBuffer; } } } } return null; } finally { lock.unlock(); } }
From source file:helma.main.Server.java
/** * The main method of the Server. Basically, we set up Applications and than * periodically check for changes in the apps.properties file, shutting down * apps or starting new ones.//from w w w . j ava 2 s . c o m */ public void run() { try { if (config.hasXmlrpcPort()) { InetSocketAddress xmlrpcPort = config.getXmlrpcPort(); String xmlparser = sysProps.getProperty("xmlparser"); if (xmlparser != null) { XmlRpc.setDriver(xmlparser); } if (xmlrpcPort.getAddress() != null) { xmlrpc = new WebServer(xmlrpcPort.getPort(), xmlrpcPort.getAddress()); } else { xmlrpc = new WebServer(xmlrpcPort.getPort()); } if (paranoid) { xmlrpc.setParanoid(true); String xallow = sysProps.getProperty("allowXmlRpc"); if (xallow != null) { StringTokenizer st = new StringTokenizer(xallow, " ,;"); while (st.hasMoreTokens()) xmlrpc.acceptClient(st.nextToken()); } } xmlrpc.start(); logger.info("Starting XML-RPC server on port " + (xmlrpcPort)); } appManager = new ApplicationManager(appsProps, this); if (xmlrpc != null) { xmlrpc.addHandler("$default", appManager); } // add shutdown hook to close running apps and servers on exit shutdownhook = new HelmaShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownhook); } catch (Exception x) { throw new RuntimeException("Error setting up Server", x); } // set the security manager. // the default implementation is helma.main.HelmaSecurityManager. try { String secManClass = sysProps.getProperty("securityManager"); if (secManClass != null) { SecurityManager secMan = (SecurityManager) Class.forName(secManClass).newInstance(); System.setSecurityManager(secMan); logger.info("Setting security manager to " + secManClass); } } catch (Exception x) { logger.error("Error setting security manager", x); } // start embedded web server if (jetty != null) { try { jetty.start(); } catch (Exception m) { throw new RuntimeException("Error starting embedded web server", m); } } // start applications appManager.startAll(); while (Thread.currentThread() == mainThread) { try { Thread.sleep(3000L); } catch (InterruptedException ie) { } try { appManager.checkForChanges(); } catch (Exception x) { logger.warn("Caught in app manager loop: " + x); } } }
From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java
@Test public void testInboxWithMessages() throws Exception { InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort()); ProtocolServer server = null;//from w w w .j a va 2s .com try { String identifier = "id"; TestPassCmdHandler handler = new TestPassCmdHandler(); handler.add("valid", new MockMailbox(identifier, MESSAGE1, MESSAGE2)); server = createServer(createProtocol(handler), address); server.bind(); POP3Client client = createClient(); client.connect(address.getAddress().getHostAddress(), address.getPort()); assertThat(client.login("valid", "valid")).isTrue(); POP3MessageInfo[] info = client.listMessages(); assertThat(info.length).isEqualTo(2); assertThat(info[0].size).isEqualTo((int) MESSAGE1.meta.getSize()); assertThat(info[1].size).isEqualTo((int) MESSAGE2.meta.getSize()); assertThat(info[0].number).isEqualTo(1); assertThat(info[1].number).isEqualTo(2); POP3MessageInfo mInfo = client.listMessage(1); assertThat(mInfo.size).isEqualTo((int) MESSAGE1.meta.getSize()); assertThat(mInfo.number).isEqualTo(1); // try to retrieve message that not exist mInfo = client.listMessage(10); assertThat(mInfo).isNull(); info = client.listUniqueIdentifiers(); assertThat(info.length).isEqualTo(2); assertThat(info[0].identifier).isEqualTo(identifier + "-" + MESSAGE1.meta.getUid()); assertThat(info[1].identifier).isEqualTo(identifier + "-" + MESSAGE2.meta.getUid()); assertThat(info[0].number).isEqualTo(1); assertThat(info[1].number).isEqualTo(2); mInfo = client.listUniqueIdentifier(1); assertThat(mInfo.identifier).isEqualTo(identifier + "-" + MESSAGE1.meta.getUid()); assertThat(mInfo.number).isEqualTo(1); // try to retrieve message that not exist mInfo = client.listUniqueIdentifier(10); assertThat(mInfo).isNull(); assertThat(client.logout()).isTrue(); } finally { if (server != null) { server.unbind(); } } }
From source file:org.opennms.test.system.api.NewTestEnvironment.java
/** * Blocks until we can connect to the PostgreSQL data port. *///from w ww.j a v a 2 s. c om private void waitForPostgres() { final ContainerAlias alias = ContainerAlias.POSTGRES; if (!isEnabled(alias)) { return; } final InetSocketAddress postgresAddr = getServiceAddress(alias, 5432); final Callable<Boolean> isConnected = new Callable<Boolean>() { @Override public Boolean call() throws Exception { try { final Socket socket = new Socket(postgresAddr.getAddress(), postgresAddr.getPort()); socket.setReuseAddress(true); final InputStream is = socket.getInputStream(); final OutputStream os = socket.getOutputStream(); os.write("\\_()_/\n".getBytes()); os.close(); is.close(); socket.close(); // good enough, not gonna try speaking the PostgreSQL protocol return true; } catch (final Throwable t) { LOG.debug("PostgreSQL connect failed: " + t.getMessage()); return null; } } }; LOG.info("************************************************************"); LOG.info("Waiting for PostgreSQL service @ {}.", postgresAddr); LOG.info("************************************************************"); await().atMost(5, MINUTES).pollInterval(10, SECONDS).until(isConnected, is(notNullValue())); }
From source file:com.all.dht.DhtManager.java
private void removeRemoteEntity(DHTValueEntity valueEntity, Boolean oversized) { AllMessage<String> deleteMessage = new AllMessage<String>(DELETE_DHT_VALUE_REQUEST_TYPE, valueEntity.getPrimaryKey().toHexString()); deleteMessage.putProperty(IS_OVERSIZED_VALUE, oversized.toString()); InetSocketAddress contactAddress = (InetSocketAddress) valueEntity.getCreator().getContactAddress(); networkingService.send(dht.getLocalNodeID().toHexString(), deleteMessage, contactAddress.getAddress().getHostAddress(), contactAddress.getPort() + 1); }
From source file:org.mahasen.node.MahasenNodeManager.java
/** * @param localport//w ww . j av a2 s. c o m * @param localaddress * @param bootport * @param bootaddress * @param registryUrl * @param env * @throws Exception */ public void bootNode(int localport, InetSocketAddress localaddress, int bootport, InetSocketAddress bootaddress, String registryUrl, Environment env) throws Exception { this.env = env; env.getParameters().setString("nat_search_policy", "never"); System.out.println("starting pastry node configuration"); // Generate the NodeIds Randomly NodeIdFactory nidFactory = new IPNodeIdFactory(bootaddress.getAddress(), localport, env); // construct the PastryNodeFactory, this is how we use rice.pastry.socket PastryNodeFactory factory; // this will resolve the localhost problem if (bootaddress.getAddress().isLoopbackAddress()) { factory = new SocketPastryNodeFactory(nidFactory, bootaddress.getAddress(), localaddress.getPort(), env); } else { factory = new SocketPastryNodeFactory(nidFactory, localaddress.getPort(), env); } // construct a node, but this does not cause it to boot node = factory.newNode(); // used for generating PastContent object Ids. // this implements the "hash function" for our DHT idf = new rice.pastry.commonapi.PastryIdFactory(env); // create a different storage root for each node String storageDirectory = "./" + baseDir + "/storage" + getNode().getId().hashCode(); storageFile = new File(storageDirectory); // registry = new RemoteRegistry(registryUrl, "admin", "admin"); //registry = Activator.getRegistryService().getRegistry(); // create the persistent part Storage store = new MahasenStorage(new PastryIdFactory(env), storageDirectory, 4 * 1024 * 1024, getNode().getEnvironment()); mahasenPastApp = new MahasenPastImpl(getNode(), new StorageManagerImpl(idf, store, new LRUCache(new MemoryStorage(idf), 512 * 1024, getNode().getEnvironment())), 3, "PastApp"); mahasenApp = new MahasenPastryApp(node); //Create the memory storage part MahasenMemoryStorage memoryStorage = new MahasenMemoryStorage(new PastryIdFactory(env), env); mahasenPastTreeApp = new MahasenPastImpl(getNode(), new StorageManagerImpl(idf, memoryStorage, new LRUCache(new MemoryStorage(idf), 512 * 1024, getNode().getEnvironment())), 1, "PastTreeApp"); getNode().boot(bootaddress); // the node may require sending several messages to fully boot into the ring synchronized (getNode()) { while (!getNode().isReady() && !getNode().joinFailed()) { // delay so we don't busy-wait node.wait(500); // abort if can't join if (getNode().joinFailed()) { throw new IOException( "Could not join the FreePastry ring. Reason:" + getNode().joinFailedReason()); } } } System.out.println("Finished creating new node " + getNode()); env.getTimeSource().sleep(10000); MahasenMsg msg = new MahasenMsg(); msg.setSendersNodeHandle(node.getLocalHandle()); NodeIdFactory rFactory = new RandomNodeIdFactory(env); }
From source file:org.waveprotocol.box.server.rpc.ServerRpcProvider.java
/** * @return a list of {@link SelectChannelConnector} each bound to a host:port * pair form the list addresses. *///from w w w . j ava 2 s . co m private List<Connector> getSelectChannelConnectors(InetSocketAddress[] httpAddresses) { List<Connector> list = Lists.newArrayList(); String[] excludeCiphers = { "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" }; SslContextFactory sslContextFactory = null; if (sslEnabled) { Preconditions.checkState(sslKeystorePath != null && !sslKeystorePath.isEmpty(), "SSL Keystore path left blank"); Preconditions.checkState(sslKeystorePassword != null && !sslKeystorePassword.isEmpty(), "SSL Keystore password left blank"); sslContextFactory = new SslContextFactory(sslKeystorePath); sslContextFactory.setKeyStorePassword(sslKeystorePassword); sslContextFactory.setRenegotiationAllowed(false); sslContextFactory.setExcludeCipherSuites(excludeCiphers); // Note: we only actually needed client auth for AuthenticationServlet. // Using Need instead of Want prevents web-sockets from working on // Chrome. sslContextFactory.setWantClientAuth(true); } for (InetSocketAddress address : httpAddresses) { ServerConnector connector; if (sslEnabled) { connector = new ServerConnector(httpServer, sslContextFactory); } else { connector = new ServerConnector(httpServer); } connector.setHost(address.getAddress().getHostAddress()); connector.setPort(address.getPort()); connector.setIdleTimeout(0); list.add(connector); } return list; }
From source file:edu.umass.cs.msocket.gns.GnsIntegration.java
/** * Register any globally unique Human Readable Name in the GNS and create a * field with the same name in that GUID to store the InetSocketAddress * information./*ww w. j a v a2 s .co m*/ * * @param name Human readable name of the service (needs to be unique * GNS-wide) * @param saddr The IP address to store for this service * @param credentials The GNS credentials to use, usually the account GUID and * default GNS (if null default GNS credentials are used) * @throws IOException */ public static void registerWithGNS(String name, InetSocketAddress saddr, GnsCredentials credentials) throws IOException { try { if (credentials == null) credentials = GnsCredentials.getDefaultCredentials(); log.trace("Looking for entity " + name + " GUID and certificates..."); GuidEntry myGuid = KeyPairUtils .getGuidEntryFromPreferences(credentials.getGnsHost() + ":" + credentials.getGnsPort(), name); final UniversalGnsClient gnsClient = credentials.getGnsClient(); /* * Take a lock on the GNS connection object to prevent concurrent queries to * the GNS on the same connection as the library is not thread-safe from * that standpoint. */ synchronized (gnsClient) { if (myGuid == null) { System.out.println("No keys found for service " + name + ". Generating new GUID and keys"); // Create a new GUID myGuid = gnsClient.guidCreate(credentials.getGuidEntry(), name); // save keys in the preference System.out.println("saving keys to local"); KeyPairUtils.saveKeyPairToPreferences(KeyPairUtils.getDefaultGnsFromPreferences(), myGuid.getEntityName(), myGuid.getGuid(), new KeyPair(myGuid.getPublicKey(), myGuid.getPrivateKey())); // storing alias in gns record, need it to find it when we have GUID // from group members gnsClient.fieldCreate(myGuid.getGuid(), GnsConstants.ALIAS_FIELD, new JSONArray().put(name), myGuid); } // Put the IP address in the GNS String ipPort = saddr.getAddress().getHostAddress() + ":" + saddr.getPort(); log.trace("Updating " + GnsConstants.SERVER_REG_ADDR + " GNSValue " + ipPort); gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.SERVER_REG_ADDR, new JSONArray().put(ipPort), myGuid); } } catch (Exception ex) { throw new IOException(ex); } }
From source file:org.spout.engine.SpoutEngine.java
@Override public Protocol getProtocol(SocketAddress socketAddress) { Protocol proto = boundProtocols.get(socketAddress); if (proto == null) { for (Map.Entry<SocketAddress, Protocol> entry : boundProtocols.entrySet()) { if (entry.getKey() instanceof InetSocketAddress && socketAddress instanceof InetSocketAddress) { InetSocketAddress key = (InetSocketAddress) entry.getKey(), given = (InetSocketAddress) socketAddress; if (key.getPort() == given.getPort() && ((given.getAddress() instanceof Inet4Address && key.getAddress().getHostAddress().equals("0.0.0.0")) || (given.getAddress() instanceof Inet6Address && key.getAddress().getHostAddress().equals("::")))) { // TODO: Make sure IPV6 works proto = entry.getValue(); break; }/* w w w. j a va 2 s . c o m*/ } } } if (proto == null) { throw new SpoutRuntimeException("No protocol for bound address!"); } return proto; }
From source file:org.apache.nutch.protocol.htmlunit.HttpResponse.java
/** * Default public constructor./*from www .j a va 2 s. co m*/ * @param http * @param url * @param datum * @throws ProtocolException * @throws IOException */ public HttpResponse(HttpBase http, URL url, CrawlDatum datum) throws ProtocolException, IOException { this.http = http; this.url = url; this.orig = url.toString(); this.base = url.toString(); if (!"http".equals(url.getProtocol()) || !!"https".equals(url.getProtocol())) throw new HttpException("Not an HTTP url:" + url); if (Http.LOG.isTraceEnabled()) { Http.LOG.trace("fetching " + url); } String path = "".equals(url.getFile()) ? "/" : url.getFile(); // some servers will redirect a request with a host line like // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they // don't want the :80... String host = url.getHost(); int port; String portString; if (url.getPort() == -1) { port = 80; portString = ""; } else { port = url.getPort(); portString = ":" + port; } Socket socket = null; try { socket = new Socket(); // create the socket socket.setSoTimeout(http.getTimeout()); // connect String sockHost = http.useProxy() ? http.getProxyHost() : host; int sockPort = http.useProxy() ? http.getProxyPort() : port; InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort); socket.connect(sockAddr, http.getTimeout()); this.conf = http.getConf(); this.htmlParseFilters = (HtmlParseFilter[]) PluginRepository.get(conf).getOrderedPlugins( HtmlParseFilter.class, HtmlParseFilter.X_POINT_ID, HtmlParseFilters.HTMLPARSEFILTER_ORDER); if (sockAddr != null && conf.getBoolean("store.ip.address", false) == true) { headers.add("_ip_", sockAddr.getAddress().getHostAddress()); } // make request OutputStream req = socket.getOutputStream(); StringBuffer reqStr = new StringBuffer("GET "); if (http.useProxy()) { reqStr.append(url.getProtocol() + "://" + host + portString + path); } else { reqStr.append(path); } reqStr.append(" HTTP/1.0\r\n"); reqStr.append("Host: "); reqStr.append(host); reqStr.append(portString); reqStr.append("\r\n"); reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n"); String userAgent = http.getUserAgent(); if ((userAgent == null) || (userAgent.length() == 0)) { if (Http.LOG.isErrorEnabled()) { Http.LOG.error("User-agent is not set!"); } } else { reqStr.append("User-Agent: "); reqStr.append(userAgent); reqStr.append("\r\n"); } reqStr.append("Accept-Language: "); reqStr.append(this.http.getAcceptLanguage()); reqStr.append("\r\n"); reqStr.append("Accept: "); reqStr.append(this.http.getAccept()); reqStr.append("\r\n"); if (datum.getModifiedTime() > 0) { reqStr.append("If-Modified-Since: " + HttpDateFormat.toString(datum.getModifiedTime())); reqStr.append("\r\n"); } reqStr.append("\r\n"); byte[] reqBytes = reqStr.toString().getBytes(); req.write(reqBytes); req.flush(); PushbackInputStream in = // process response new PushbackInputStream(new BufferedInputStream(socket.getInputStream(), Http.BUFFER_SIZE), Http.BUFFER_SIZE); StringBuffer line = new StringBuffer(); boolean haveSeenNonContinueStatus = false; while (!haveSeenNonContinueStatus) { // parse status code line this.code = parseStatusLine(in, line); // parse headers parseHeaders(in, line); haveSeenNonContinueStatus = code != 100; // 100 is "Continue" } if (this.code == 200 && !url.toString().endsWith("robots.txt")) { readPlainContent(url); } else { readPlainContent(in); } try { byte[] decodeContent = null; String contentEncoding = getHeader(Response.CONTENT_ENCODING); if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) { decodeContent = http.processGzipEncoded(content, url); } else if ("deflate".equals(contentEncoding)) { decodeContent = http.processDeflateEncoded(content, url); } else { if (Http.LOG.isTraceEnabled()) { Http.LOG.trace("fetched " + content.length + " bytes from " + url); } } if (decodeContent != null) { content = decodeContent; } } catch (Exception e) { headers.remove(Response.CONTENT_ENCODING); } } finally { if (socket != null) socket.close(); } }