List of usage examples for java.net InetSocketAddress getAddress
public final InetAddress getAddress()
From source file:de.jaetzold.networking.SimpleServiceDiscovery.java
/** * Send a SSDP search message with the given search target (ST) and return a list of received responses. *//*from w w w . ja v a2s. c o m*/ public Map<String, URL> discover(String searchTarget) { Log.d("HUE", "ServiceDiscovery.discover"); final InetSocketAddress address; // standard multicast port for SSDP try { // multicast address with administrative scope address = new InetSocketAddress(InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT); //address = InetAddress.getByName(MULTICAST_ADDRESS); } catch (UnknownHostException e) { e.printStackTrace(); throw new IllegalStateException("Can not get multicast address", e); } final MulticastSocket socket; try { socket = new MulticastSocket(null); InetAddress localhost = getAndroidLocalIP(); InetSocketAddress srcAddress = new InetSocketAddress(localhost, MULTICAST_PORT); Log.d("HUE", "" + srcAddress.getAddress()); socket.bind(srcAddress); Log.d("HUE", "step 1"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Can not create multicast socket"); } try { socket.setSoTimeout(socketTimeout); Log.d("HUE", "step 2"); } catch (SocketException e) { e.printStackTrace(); throw new IllegalStateException("Can not set socket timeout", e); } try { socket.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS)); Log.d("HUE", "step 3"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Can not make multicast socket joinGroup " + address, e); } try { socket.setTimeToLive(ttl); Log.d("HUE", "step 4"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Can not set TTL " + ttl, e); } final byte[] transmitBuffer; try { transmitBuffer = constructSearchMessage(searchTarget).getBytes(CHARSET_NAME); Log.d("HUE", "step 5"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new IllegalStateException("WTF? " + CHARSET_NAME + " is not supported?", e); } DatagramPacket packet = null; try { packet = new DatagramPacket(transmitBuffer, transmitBuffer.length, address); Log.d("HUE", "step 6"); } catch (SocketException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { socket.send(packet); Log.d("HUE", "step 7"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Can not send search request", e); } Map<String, URL> result = new HashMap<String, URL>(); byte[] receiveBuffer = new byte[1536]; while (true) { try { Log.d("HUE", "sending packets"); final DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length, InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT); socket.receive(receivePacket); //Log.d("HUE", new String(receivePacket.getData())); HueBridge response = parseResponsePacket(receivePacket); if (response != null) { Log.d("HUE", "resonse not null"); ////System.out.println("resonse not null"); result.put(response.getUDN(), response.getBaseUrl()); } else { Log.d("HUE", "no bridge"); } } catch (SocketTimeoutException e) { Log.e("HUE", "timeout exception"); break; } catch (IOException e) { throw new IllegalStateException("Problem receiving search responses", e); } } return result; }
From source file:edu.umass.cs.reconfiguration.deprecated.ReconfigurableClient.java
private InetSocketAddress getFirstRCReplica(boolean offset) { InetSocketAddress address = this.getReconfigurators().iterator().next(); return offset ? new InetSocketAddress(address.getAddress(), ActiveReplica.getClientFacingPort(address.getPort())) : address;/*from w w w . jav a2s . com*/ }
From source file:org.apache.hadoop.hdfs.qjournal.server.JournalNodeJournalSyncer.java
/** * Recovers a single segment/*from ww w . j a va 2s. c om*/ * * @param elf * descriptor of the segment to be recovered * @param task * contains journal description * @throws IOException */ void recoverSegments(SyncTask task) throws IOException { // obtain the list of segments that are valid if (!prepareRecovery(task)) { return; } // iterate through all nodes for (InetSocketAddress jn : journalNodes) { if (isLocalIpAddress(jn.getAddress()) && jn.getPort() == journalNode.getPort()) { // we do not need to talk to ourselves continue; } try { // get manifest for log that we care about List<EditLogFile> remoteLogFiles = getManifest(jn, task.journal, task.recoveryStartTxid); // go through all remote segments for (EditLogFile relf : remoteLogFiles) { recoverSegment(jn, relf, task); } // if we are done, there is no need to iterate more if (!task.hasMissingValidSegments()) { LOG.info(logMsg + "recovery finished."); break; } } catch (Exception e) { LOG.error(logMsg + "error", e); continue; } } }
From source file:org.jolokia.jvmagent.handler.JolokiaHttpHandler.java
@SuppressWarnings({ "PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause" }) public void doHandle(HttpExchange pExchange) throws IOException { if (requestHandler == null) { throw new IllegalStateException("Handler not yet started"); }// ww w.j a v a 2 s . c o m JSONAware json = null; URI uri = pExchange.getRequestURI(); ParsedUri parsedUri = new ParsedUri(uri, context); try { // Check access policy InetSocketAddress address = pExchange.getRemoteAddress(); requestHandler.checkAccess(getHostName(address), address.getAddress().getHostAddress(), extractOriginOrReferer(pExchange)); String method = pExchange.getRequestMethod(); // Dispatch for the proper HTTP request method if ("GET".equalsIgnoreCase(method)) { setHeaders(pExchange); json = executeGetRequest(parsedUri); } else if ("POST".equalsIgnoreCase(method)) { setHeaders(pExchange); json = executePostRequest(pExchange, parsedUri); } else if ("OPTIONS".equalsIgnoreCase(method)) { performCorsPreflightCheck(pExchange); } else { throw new IllegalArgumentException("HTTP Method " + method + " is not supported."); } } catch (Throwable exp) { json = requestHandler.handleThrowable( exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp); } finally { sendResponse(pExchange, parsedUri, json); } }
From source file:org.apache.hadoop.realtime.client.ClientServiceDelegate.java
private DragonClientProtocol getProxy() throws YarnRemoteException { if (realProxy != null) { return realProxy; }//from w w w . j a v a2 s. c o m ApplicationReport application = rm.getApplicationReport(appId); if (application != null) { trackingUrl = application.getTrackingUrl(); } String serviceAddr = null; while (application == null || YarnApplicationState.RUNNING == application.getYarnApplicationState()) { try { if (application.getHost() == null || "".equals(application.getHost())) { LOG.debug("AM not assigned to Job. Waiting to get the AM ..."); Thread.sleep(2000); LOG.debug("Application state is " + application.getYarnApplicationState()); application = rm.getApplicationReport(appId); continue; } if (!conf.getBoolean(DragonJobConfig.JOB_AM_ACCESS_DISABLED, false)) { UserGroupInformation newUgi = UserGroupInformation .createRemoteUser(UserGroupInformation.getCurrentUser().getUserName()); serviceAddr = application.getHost() + ":" + application.getRpcPort(); if (UserGroupInformation.isSecurityEnabled()) { String clientTokenEncoded = application.getClientToken(); Token<ApplicationTokenIdentifier> clientToken = new Token<ApplicationTokenIdentifier>(); clientToken.decodeFromUrlString(clientTokenEncoded); // RPC layer client expects ip:port as service for tokens InetSocketAddress addr = NetUtils.createSocketAddr(application.getHost(), application.getRpcPort()); clientToken.setService(new Text(addr.getAddress().getHostAddress() + ":" + addr.getPort())); newUgi.addToken(clientToken); } LOG.debug("Connecting to " + serviceAddr); final String tempStr = serviceAddr; realProxy = newUgi.doAs(new PrivilegedExceptionAction<DragonClientProtocol>() { @Override public DragonClientProtocol run() throws IOException { return instantiateAMProxy(tempStr); } }); } else { if (!amAclDisabledStatusLogged) { LOG.info("Network ACL closed to AM for job " + jobId + ". Not going to try to reach the AM."); amAclDisabledStatusLogged = true; } return getNotRunningJob(null, JobState.RUNNING); } return realProxy; } catch (IOException e) { //possibly the AM has crashed //there may be some time before AM is restarted //keep retrying by getting the address from RM LOG.info("Could not connect to " + serviceAddr + ". Waiting for getting the latest AM address..."); try { Thread.sleep(2000); } catch (InterruptedException e1) { LOG.warn("getProxy() call interruped", e1); throw new YarnException(e1); } application = rm.getApplicationReport(appId); } catch (InterruptedException e) { LOG.warn("getProxy() call interruped", e); throw new YarnException(e); } } /** we just want to return if its allocating, so that we don't * block on it. This is to be able to return job status * on an allocating Application. */ String user = application.getUser(); if (user == null) { throw RPCUtil.getRemoteException("User is not set in the application report"); } if (application.getYarnApplicationState() == YarnApplicationState.NEW || application.getYarnApplicationState() == YarnApplicationState.SUBMITTED) { realProxy = null; return getNotRunningJob(application, JobState.NEW); } if (application.getYarnApplicationState() == YarnApplicationState.FAILED) { realProxy = null; return getNotRunningJob(application, JobState.FAILED); } if (application.getYarnApplicationState() == YarnApplicationState.KILLED) { realProxy = null; return getNotRunningJob(application, JobState.KILLED); } return realProxy; }
From source file:com.devoteam.srit.xmlloader.http.nio.NIOSocketServerListener.java
public void acceptReady() { try {//from w w w . jav a 2s . c o m SocketChannel socketChannel = this.channel.accept(); NIOSocketServerHttp socketServerHttp = new NIOSocketServerHttp(); HybridSocket socket = new HybridSocket(socketServerHttp); InetSocketAddress remoteInetSocketAddress = (InetSocketAddress) socketChannel.socket() .getRemoteSocketAddress(); InetSocketAddress localInetSocketAddress = (InetSocketAddress) socketChannel.socket() .getLocalSocketAddress(); String connectionName = "HTTPServerConnection" + Stack.nextTransactionId(); String remoteHost = remoteInetSocketAddress.getAddress().getHostAddress(); String remotePort = Integer.toString(remoteInetSocketAddress.getPort()); String localHost = localInetSocketAddress.getAddress().getHostAddress(); String localPort = Integer.toString(localInetSocketAddress.getPort()); NIOChannelHttp channelHTTP = new NIOChannelHttp(connectionName, localHost, localPort, remoteHost, remotePort, StackFactory.PROTOCOL_HTTP, secure); DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection(); socketServerHttp.init(serverConnection, channelHTTP); channelHTTP.setSocketServerHttp(socketServerHttp); StackFactory.getStack(StackFactory.PROTOCOL_HTTP).openChannel(channelHTTP); if (socketChannel instanceof SSLSocketChannel) StackHttp.ioReactor.openTLS((SSLSocketChannel) socketChannel, socket); else StackHttp.ioReactor.openTCP(socketChannel, socket); serverConnection.bind(socket, new BasicHttpParams()); } catch (Exception e) { GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.PROTOCOL, e, "Exception in SocketServerListener secure=", secure); e.printStackTrace(); } }
From source file:edu.umass.cs.reconfiguration.deprecated.ReconfigurableClient.java
private InetSocketAddress getRandomRCReplica(boolean offset) { int index = (int) (this.getReconfigurators().size() * Math.random()); InetSocketAddress address = (InetSocketAddress) (this.getReconfigurators().toArray()[index]); return offset ? new InetSocketAddress(address.getAddress(), ActiveReplica.getClientFacingPort(address.getPort())) : address;//from w w w .j a v a 2s .com }
From source file:edu.umass.cs.msocket.proxy.ProxyGnsPublisher.java
/** * Establish a connection with the GNS, register the proxy in the proxy group, * start a monitoring socket and register its IP in the GNS, * /*from w w w . j a va 2s. c om*/ * @throws Exception */ public void registerProxyInGns() throws Exception { logger.info("Looking for proxy " + proxyName + " GUID and certificates..."); GuidEntry myGuid = KeyPairUtils.getGuidEntryFromPreferences( gnsCredentials.getGnsHost() + ":" + gnsCredentials.getGnsPort(), proxyName); final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient(); if (myGuid == null) { logger.info("No keys found for proxy " + proxyName + ". Generating new GUID and keys"); myGuid = gnsClient.guidCreate(gnsCredentials.getGuidEntry(), proxyName); } logger.info("Proxy has guid " + myGuid.getGuid()); // Determine our IP String sIp = null; BufferedReader in; InetAddress addr; try { addr = ((InetSocketAddress) proxySocketAddres).getAddress(); if (addr != null && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && !addr.isSiteLocalAddress()) sIp = addr.getHostAddress(); } catch (Exception e) { logger.log(Level.WARNING, "Failed to resolve proxy address " + proxySocketAddres, e); } if (sIp == null) { logger.warning("Local proxy address (" + proxySocketAddres + ") does not seem to be a public address"); try { logger.info("Determining local IP"); // Determine our external IP address by contacting http://icanhazip.com URL whatismyip = new URL("http://icanhazip.com"); in = new BufferedReader(new InputStreamReader(whatismyip.openStream())); sIp = in.readLine(); in.close(); } catch (Exception e) { } } ProxyInfo proxyInfo = new ProxyInfo(myGuid.getGuid(), proxyName, sIp); try { // Contact http://freegeoip.net/csv/[IP] to resolve IP address location URL locator = new URL("http://freegeoip.net/csv/" + sIp); in = new BufferedReader(new InputStreamReader(locator.openStream())); String csv = in.readLine(); in.close(); // Read location result StringTokenizer st = new StringTokenizer(csv, ","); if (!st.hasMoreTokens()) throw new IOException("Failed to read IP"); st.nextToken(); // IP if (!st.hasMoreTokens()) throw new IOException("Failed to read country code"); String countryCode = st.nextToken().replace("\"", ""); proxyInfo.setCountryCode(countryCode); if (!st.hasMoreTokens()) throw new IOException("Failed to read country name"); String countryName = st.nextToken().replace("\"", ""); proxyInfo.setCountryName(countryName); if (!st.hasMoreTokens()) throw new IOException("Failed to read state code"); String stateCode = st.nextToken().replace("\"", ""); proxyInfo.setStateCode(stateCode); if (!st.hasMoreTokens()) throw new IOException("Failed to read state name"); String stateName = st.nextToken().replace("\"", ""); proxyInfo.setStateName(stateName); if (!st.hasMoreTokens()) throw new IOException("Failed to read city"); String city = st.nextToken().replace("\"", ""); proxyInfo.setCity(city); if (!st.hasMoreTokens()) throw new IOException("Failed to read zip"); String zip = st.nextToken().replace("\"", ""); proxyInfo.setZipCode(zip); if (!st.hasMoreTokens()) throw new IOException("Failed to read latitude"); String latitudeStr = st.nextToken().replace("\"", ""); double latitude = Double.parseDouble(latitudeStr); if (!st.hasMoreTokens()) throw new IOException("Failed to read longitude"); String longitudeStr = st.nextToken().replace("\"", ""); double longitude = Double.parseDouble(longitudeStr); proxyInfo.setLatLong(new GlobalPosition(latitude, longitude, 0)); } catch (Exception e) { logger.log(Level.WARNING, "Failed to locate IP address " + e); } // Look for the group GUID String groupGuid = gnsClient.lookupGuid(proxyGroupName); // Check if we are a member of the group boolean isVerified = false; try { JSONArray members = gnsClient.groupGetMembers(groupGuid, myGuid); for (int i = 0; i < members.length(); i++) { if (myGuid.getGuid().equals(members.get(i))) { isVerified = true; break; } } } catch (Exception e) { /* * At this point we couldn't get or parse the member list probably because * we don't have read access to it. This means we are not a verified * member. */ logger.log(Level.INFO, "Could not access the proxy group member list because we are not likely a group member yet (" + e + ")"); } // Make sure we advertise ourselves as a proxy and make the field readable // by everyone gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.SERVICE_TYPE_FIELD, new JSONArray().put(GnsConstants.PROXY_SERVICE), myGuid); gnsClient.aclAdd(AccessType.READ_WHITELIST, myGuid, GnsConstants.SERVICE_TYPE_FIELD, null); // Publish external IP (readable by everyone) InetSocketAddress externalIP = (InetSocketAddress) proxySocketAddres; gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.PROXY_EXTERNAL_IP_FIELD, new JSONArray().put(externalIP.getAddress().getHostAddress() + ":" + externalIP.getPort()), myGuid); gnsClient.aclAdd(AccessType.READ_WHITELIST, myGuid, GnsConstants.PROXY_EXTERNAL_IP_FIELD, null); // Update our location if geolocation resolution worked if (proxyInfo.getLatLong() != null) gnsClient.setLocation(proxyInfo.getLatLong().getLongitude(), proxyInfo.getLatLong().getLatitude(), myGuid); if (!isVerified) { logger.log(Level.WARNING, "This proxy has not been verified yet, it will stay in the unverified list until it gets added to the proxy group"); } gnsTimer = new GnsTimerKeepalive(gnsCredentials, myGuid, 1000); gnsTimer.start(); }
From source file:org.andstatus.app.net.http.TlsSniSocketFactory.java
@Override public Socket connectSocket(int timeout, Socket plain, HttpHost host, InetSocketAddress remoteAddr, InetSocketAddress localAddr, HttpContext context) throws IOException { MyLog.d(this, "Preparing direct SSL connection (without proxy) to " + host); // we'll rather use an SSLSocket directly plain.close();//from w w w . j a v a2 s .com // create a plain SSL socket, but don't do hostname/certificate verification yet SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(remoteAddr.getAddress(), host.getPort()); // connect, set SNI, shake hands, verify, print connection info connectWithSNI(ssl, host.getHostName()); return ssl; }
From source file:org.apache.hadoop.hbase.mapreduce.TableInputFormatBase.java
/** * Calculates the splits that will serve as input for the map tasks. The * number of splits matches the number of regions in a table. * * @param context The current job context. * @return The list of input splits./*from w w w. j a v a2s .com*/ * @throws IOException When creating the list of splits fails. * @see org.apache.hadoop.mapreduce.InputFormat#getSplits( * org.apache.hadoop.mapreduce.JobContext) */ @Override public List<InputSplit> getSplits(JobContext context) throws IOException { if (table == null) { throw new IOException("No table was provided."); } // Get the name server address and the default value is null. this.nameServer = context.getConfiguration().get("hbase.nameserver.address", null); RegionSizeCalculator sizeCalculator = new RegionSizeCalculator(table); Pair<byte[][], byte[][]> keys = table.getStartEndKeys(); if (keys == null || keys.getFirst() == null || keys.getFirst().length == 0) { HRegionLocation regLoc = table.getRegionLocation(HConstants.EMPTY_BYTE_ARRAY, false); if (null == regLoc) { throw new IOException("Expecting at least one region."); } List<InputSplit> splits = new ArrayList<InputSplit>(1); long regionSize = sizeCalculator.getRegionSize(regLoc.getRegionInfo().getRegionName()); TableSplit split = new TableSplit(table.getName(), HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY, regLoc.getHostnamePort().split(Addressing.HOSTNAME_PORT_SEPARATOR)[0], regionSize); splits.add(split); return splits; } List<InputSplit> splits = new ArrayList<InputSplit>(keys.getFirst().length); for (int i = 0; i < keys.getFirst().length; i++) { if (!includeRegionInSplit(keys.getFirst()[i], keys.getSecond()[i])) { continue; } HRegionLocation location = table.getRegionLocation(keys.getFirst()[i], false); // The below InetSocketAddress creation does a name resolution. InetSocketAddress isa = new InetSocketAddress(location.getHostname(), location.getPort()); if (isa.isUnresolved()) { LOG.warn("Failed resolve " + isa); } InetAddress regionAddress = isa.getAddress(); String regionLocation; try { regionLocation = reverseDNS(regionAddress); } catch (NamingException e) { LOG.warn("Cannot resolve the host name for " + regionAddress + " because of " + e); regionLocation = location.getHostname(); } byte[] startRow = scan.getStartRow(); byte[] stopRow = scan.getStopRow(); // determine if the given start an stop key fall into the region if ((startRow.length == 0 || keys.getSecond()[i].length == 0 || Bytes.compareTo(startRow, keys.getSecond()[i]) < 0) && (stopRow.length == 0 || Bytes.compareTo(stopRow, keys.getFirst()[i]) > 0)) { byte[] splitStart = startRow.length == 0 || Bytes.compareTo(keys.getFirst()[i], startRow) >= 0 ? keys.getFirst()[i] : startRow; byte[] splitStop = (stopRow.length == 0 || Bytes.compareTo(keys.getSecond()[i], stopRow) <= 0) && keys.getSecond()[i].length > 0 ? keys.getSecond()[i] : stopRow; byte[] regionName = location.getRegionInfo().getRegionName(); long regionSize = sizeCalculator.getRegionSize(regionName); TableSplit split = new TableSplit(table.getName(), splitStart, splitStop, regionLocation, regionSize); splits.add(split); if (LOG.isDebugEnabled()) { LOG.debug("getSplits: split -> " + i + " -> " + split); } } } return splits; }