List of usage examples for java.net InetAddress isLoopbackAddress
public boolean isLoopbackAddress()
From source file:com.photon.phresco.framework.rest.api.UtilService.java
private boolean isRequestFromLocalMachine(InetAddress addr) { // Check if the address is a valid special local or loop back if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) return true; // Check if the address is defined on any interface try {// w ww. j a v a 2 s. com return NetworkInterface.getByInetAddress(addr) != null; } catch (SocketException e) { return false; } }
From source file:com.turt2live.xmail.mail.Mail.java
/** * Determines if this mail is from this server. This only verifies if the mail is from a Minecraft server (this one specifically). * If the mail is from a website, desktop application, or otherwise not a Minecraft server then this will return true as * * @return true if this mail is to be considered from this server, false otherwise *///from w w w .ja va 2 s . c o m public boolean fromThisServer() { String ip = getServerSender(); if (ip == null) { return true; } try { InetAddress add = InetAddress.getByName(ip); if (add.isAnyLocalAddress() || add.isLoopbackAddress()) { return true; } } catch (UnknownHostException e) { e.printStackTrace(); } return XMailConfig.getIP().equalsIgnoreCase(ip); }
From source file:org.deviceconnect.android.deviceplugin.chromecast.profile.ChromeCastMediaPlayerProfile.java
/** * IP??/*from w ww.j a va 2 s.c o m*/ * * @param ?? * @return IP */ private String getIpAddress() { try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement(); Enumeration<InetAddress> ipAddrs = networkInterface.getInetAddresses(); while (ipAddrs.hasMoreElements()) { InetAddress ip = (InetAddress) ipAddrs.nextElement(); String ipStr = ip.getHostAddress(); if (!ip.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipStr)) { return ipStr; } } } } catch (SocketException e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } } return null; }
From source file:com.petalmd.armor.util.SecurityUtil.java
public static InetAddress getProxyResolvedHostAddressFromRequest(final RestRequest request, final Settings settings) throws UnknownHostException { // this.logger.debug(request.getClass().toString()); final String oaddr = ((InetSocketAddress) request.getRemoteAddress()).getHostString(); // this.logger.debug("original hostname: " + addr); String raddr = oaddr;//ww w. j a v a 2 s. c o m if (oaddr == null || oaddr.isEmpty()) { throw new UnknownHostException("Original host is <null> or <empty>"); } final InetAddress iaddr = InetAddress.getByName(oaddr); final String xForwardedForHeader = settings.get(ConfigConstants.ARMOR_HTTP_XFORWARDEDFOR_HEADER, "X-Forwarded-For"); if (xForwardedForHeader != null && !xForwardedForHeader.isEmpty()) { final String xForwardedForValue = request.header(xForwardedForHeader); //logger.trace("xForwardedForHeader is " + xForwardedForHeader + ":" + xForwardedForValue); final String[] xForwardedTrustedProxies = settings .getAsArray(ConfigConstants.ARMOR_HTTP_XFORWARDEDFOR_TRUSTEDPROXIES); final boolean xForwardedEnforce = settings .getAsBoolean(ConfigConstants.ARMOR_HTTP_XFORWARDEDFOR_ENFORCE, false); if (xForwardedForValue != null && !xForwardedForValue.isEmpty()) { final List<String> addresses = Arrays.asList(xForwardedForValue.replace(" ", "").split(",")); final List<String> proxiesPassed = new ArrayList<String>(addresses.subList(1, addresses.size())); if (xForwardedTrustedProxies.length == 0) { throw new UnknownHostException("No trusted proxies"); } proxiesPassed.removeAll(Arrays.asList(xForwardedTrustedProxies)); //logger.debug(proxiesPassed.size() + "/" + proxiesPassed); if (proxiesPassed.size() == 0 && (Arrays.asList(xForwardedTrustedProxies).contains(oaddr) || iaddr.isLoopbackAddress())) { raddr = addresses.get(0).trim(); } else { throw new UnknownHostException("Not all proxies are trusted"); } } else { if (xForwardedEnforce) { throw new UnknownHostException("Forward header enforced but not present"); } } } if (raddr == null || raddr.isEmpty()) { throw new UnknownHostException("Host is <null> or <empty>"); } if (raddr.equals(oaddr)) { return iaddr; } else { // if null or "" then loopback is returned return InetAddress.getByName(raddr); } }
From source file:com.floragunn.searchguard.util.SecurityUtil.java
public static InetAddress getProxyResolvedHostAddressFromRequest(final RestRequest request, final Settings settings) throws UnknownHostException { // this.logger.debug(request.getClass().toString()); final String oaddr = ((InetSocketAddress) request.getRemoteAddress()).getHostString(); // this.logger.debug("original hostname: " + addr); String raddr = oaddr;/*w w w. ja v a2 s .com*/ if (oaddr == null || oaddr.isEmpty()) { throw new UnknownHostException("Original host is <null> or <empty>"); } final InetAddress iaddr = InetAddress.getByName(oaddr); final String xForwardedForHeader = settings.get(ConfigConstants.SEARCHGUARD_HTTP_XFORWARDEDFOR_HEADER, "X-Forwarded-For"); if (xForwardedForHeader != null && !xForwardedForHeader.isEmpty()) { final String xForwardedForValue = request.header(xForwardedForHeader); //logger.trace("xForwardedForHeader is " + xForwardedForHeader + ":" + xForwardedForValue); final String[] xForwardedTrustedProxies = settings .getAsArray(ConfigConstants.SEARCHGUARD_HTTP_XFORWARDEDFOR_TRUSTEDPROXIES); final boolean xForwardedEnforce = settings .getAsBoolean(ConfigConstants.SEARCHGUARD_HTTP_XFORWARDEDFOR_ENFORCE, false); if (xForwardedForValue != null && !xForwardedForValue.isEmpty()) { final List<String> addresses = Arrays.asList(xForwardedForValue.replace(" ", "").split(",")); final List<String> proxiesPassed = new ArrayList<String>(addresses.subList(1, addresses.size())); if (xForwardedTrustedProxies.length == 0) { throw new UnknownHostException("No trusted proxies"); } proxiesPassed.removeAll(Arrays.asList(xForwardedTrustedProxies)); //logger.debug(proxiesPassed.size() + "/" + proxiesPassed); if (proxiesPassed.size() == 0 && (Arrays.asList(xForwardedTrustedProxies).contains(oaddr) || iaddr.isLoopbackAddress())) { raddr = addresses.get(0).trim(); } else { throw new UnknownHostException("Not all proxies are trusted"); } } else { if (xForwardedEnforce) { throw new UnknownHostException("Forward header enforced but not present"); } } } if (raddr == null || raddr.isEmpty()) { throw new UnknownHostException("Host is <null> or <empty>"); } if (raddr.equals(oaddr)) { return iaddr; } else { // if null or "" then loopback is returned return InetAddress.getByName(raddr); } }
From source file:com.aimluck.eip.mail.util.ALMailUtils.java
public static String getLocalurl() { EipMCompany record = ALEipUtils.getEipMCompany("1"); String localurl = ""; try {//from w ww . ja v a 2s . co m String ipaddress = record.getIpaddressInternal(); if (null == ipaddress || "".equals(ipaddress)) { Enumeration<NetworkInterface> enuIfs = NetworkInterface.getNetworkInterfaces(); if (null != enuIfs) { while (enuIfs.hasMoreElements()) { NetworkInterface ni = enuIfs.nextElement(); Enumeration<InetAddress> enuAddrs = ni.getInetAddresses(); while (enuAddrs.hasMoreElements()) { InetAddress in4 = enuAddrs.nextElement(); if (!in4.isLoopbackAddress()) { ipaddress = in4.getHostAddress(); } } } } } Integer port_internal = record.getPortInternal(); if (null == port_internal) { port_internal = 80; } localurl = ALServletUtils.getAccessUrl(ipaddress, port_internal, false); } catch (SocketException e) { logger.error("ALMailUtils.getLocalurl", e); } return localurl; }
From source file:com.vuze.plugin.azVPN_PIA.Checker.java
private int findBindingAddress(File pathPIAManagerData, StringBuilder sReply) { int newStatusID = -1; // Find our VPN binding (interface) address. Checking UDP is the best bet, // since TCP and http might be proxied List<PRUDPPacketHandler> handlers = PRUDPPacketHandlerFactory.getHandlers(); if (handlers.size() == 0) { PRUDPReleasablePacketHandler releasableHandler = PRUDPPacketHandlerFactory.getReleasableHandler(0); handlers = PRUDPPacketHandlerFactory.getHandlers(); releasableHandler.release();/* ww w .j a v a2 s . c o m*/ } if (handlers.size() == 0) { addLiteralReply(sReply, CHAR_BAD + " No UDP Handlers"); newStatusID = STATUS_ID_BAD; } else { InetAddress bindIP = handlers.get(0).getBindIP(); // The "Any" field is equivalent to 0.0.0.0 in dotted-quad notation, which is unbound. // "Loopback" is 127.0.0.1, which is bound when Vuze can't bind to // user specified interface (ie. kill switched) if (bindIP.isAnyLocalAddress() || bindIP.isLoopbackAddress()) { newStatusID = handleUnboundOrLoopback(bindIP, sReply); if (newStatusID == STATUS_ID_BAD) { return newStatusID; } } else { newStatusID = handleBound(bindIP, sReply); } } return newStatusID; }
From source file:eu.faircode.adblocker.ServiceSinkhole.java
public static List<InetAddress> getDns(Context context) { List<InetAddress> listDns = new ArrayList<>(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); List<String> sysDns = Util.getDefaultDNS(context); String vpnDns = prefs.getString("dns", null); Log.i(TAG, "DNS system=" + TextUtils.join(",", sysDns) + " VPN=" + vpnDns); if (vpnDns != null) try {/* w w w .jav a 2 s . co m*/ InetAddress dns = InetAddress.getByName(vpnDns); if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress())) listDns.add(dns); } catch (Throwable ignored) { } for (String def_dns : sysDns) try { InetAddress ddns = InetAddress.getByName(def_dns); if (!listDns.contains(ddns) && !(ddns.isLoopbackAddress() || ddns.isAnyLocalAddress())) listDns.add(ddns); } catch (Throwable ignored) { } return listDns; }
From source file:com.landenlabs.all_devtool.NetFragment.java
public void updateList() { // Time today = new Time(Time.getCurrentTimezone()); // today.setToNow(); // today.format(" %H:%M:%S") Date dt = new Date(); m_titleTime.setText(m_timeFormat.format(dt)); boolean expandAll = m_list.isEmpty(); m_list.clear();//from w w w . ja v a2 s. co m // Swap colors int color = m_rowColor1; m_rowColor1 = m_rowColor2; m_rowColor2 = color; ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE); try { String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID); addBuild("Android ID", androidIDStr); try { AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext()); final String adIdStr = adInfo.getId(); final boolean isLAT = adInfo.isLimitAdTrackingEnabled(); addBuild("Ad ID", adIdStr); } catch (IOException e) { // Unrecoverable error connecting to Google Play services (e.g., // the old version of the service doesn't support getting AdvertisingId). } catch (GooglePlayServicesNotAvailableException e) { // Google Play services is not available entirely. } /* try { InstanceID instanceID = InstanceID.getInstance(getContext()); if (instanceID != null) { // Requires a Google Developer project ID. String authorizedEntity = "<need to make this on google developer site>"; instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); addBuild("Instance ID", instanceID.getId()); } } catch (Exception ex) { } */ ConfigurationInfo info = actMgr.getDeviceConfigurationInfo(); addBuild("OpenGL", info.getGlEsVersion()); } catch (Exception ex) { m_log.e(ex.getMessage()); } // --------------- Connection Services ------------- try { ConnectivityManager connMgr = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = connMgr.getActiveNetworkInfo(); if (netInfo != null) { Map<String, String> netListStr = new LinkedHashMap<String, String>(); putIf(netListStr, "Available", "Yes", netInfo.isAvailable()); putIf(netListStr, "Connected", "Yes", netInfo.isConnected()); putIf(netListStr, "Connecting", "Yes", !netInfo.isConnected() && netInfo.isConnectedOrConnecting()); putIf(netListStr, "Roaming", "Yes", netInfo.isRoaming()); putIf(netListStr, "Extra", netInfo.getExtraInfo(), !TextUtils.isEmpty(netInfo.getExtraInfo())); putIf(netListStr, "WhyFailed", netInfo.getReason(), !TextUtils.isEmpty(netInfo.getReason())); if (Build.VERSION.SDK_INT >= 16) { putIf(netListStr, "Metered", "Avoid heavy use", connMgr.isActiveNetworkMetered()); } netListStr.put("NetworkType", netInfo.getTypeName()); if (connMgr.getAllNetworkInfo().length > 1) { netListStr.put("Available Networks:", " "); for (NetworkInfo netI : connMgr.getAllNetworkInfo()) { if (netI.isAvailable()) { netListStr.put(" " + netI.getTypeName(), netI.isAvailable() ? "Yes" : "No"); } } } if (netInfo.isConnected()) { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { if (inetAddress.getHostAddress() != null) { String ipType = (inetAddress instanceof Inet4Address) ? "IPv4" : "IPv6"; netListStr.put(intf.getName() + " " + ipType, inetAddress.getHostAddress()); } // if (!TextUtils.isEmpty(inetAddress.getHostName())) // listStr.put( "HostName", inetAddress.getHostName()); } } } } catch (Exception ex) { m_log.e("Network %s", ex.getMessage()); } } addBuild("Network...", netListStr); } } catch (Exception ex) { m_log.e("Network %s", ex.getMessage()); } // --------------- Telephony Services ------------- TelephonyManager telephonyManager = (TelephonyManager) getActivity() .getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { Map<String, String> cellListStr = new LinkedHashMap<String, String>(); try { cellListStr.put("Version", telephonyManager.getDeviceSoftwareVersion()); cellListStr.put("Number", telephonyManager.getLine1Number()); cellListStr.put("Service", telephonyManager.getNetworkOperatorName()); cellListStr.put("Roaming", telephonyManager.isNetworkRoaming() ? "Yes" : "No"); cellListStr.put("Type", getNetworkTypeName(telephonyManager.getNetworkType())); if (Build.VERSION.SDK_INT >= 17) { if (telephonyManager.getAllCellInfo() != null) { for (CellInfo cellInfo : telephonyManager.getAllCellInfo()) { String cellName = cellInfo.getClass().getSimpleName(); int level = 0; if (cellInfo instanceof CellInfoCdma) { level = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel(); } else if (cellInfo instanceof CellInfoGsm) { level = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel(); } else if (cellInfo instanceof CellInfoLte) { level = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel(); } else if (cellInfo instanceof CellInfoWcdma) { if (Build.VERSION.SDK_INT >= 18) { level = ((CellInfoWcdma) cellInfo).getCellSignalStrength().getLevel(); } } cellListStr.put(cellName, "Level% " + String.valueOf(100 * level / 4)); } } } for (NeighboringCellInfo cellInfo : telephonyManager.getNeighboringCellInfo()) { int level = cellInfo.getRssi(); cellListStr.put("Cell level%", String.valueOf(100 * level / 31)); } } catch (Exception ex) { m_log.e("Cell %s", ex.getMessage()); } if (!cellListStr.isEmpty()) { addBuild("Cell...", cellListStr); } } // --------------- Bluetooth Services (API18) ------------- if (Build.VERSION.SDK_INT >= 18) { try { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter != null) { Map<String, String> btListStr = new LinkedHashMap<String, String>(); btListStr.put("Enabled", bluetoothAdapter.isEnabled() ? "yes" : "no"); btListStr.put("Name", bluetoothAdapter.getName()); btListStr.put("ScanMode", String.valueOf(bluetoothAdapter.getScanMode())); btListStr.put("State", String.valueOf(bluetoothAdapter.getState())); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView btListStr.put("Paired:" + device.getName(), device.getAddress()); } } BluetoothManager btMgr = (BluetoothManager) getActivity() .getSystemService(Context.BLUETOOTH_SERVICE); if (btMgr != null) { // btMgr.getAdapter(). } addBuild("Bluetooth", btListStr); } } catch (Exception ex) { } } // --------------- Wifi Services ------------- final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext() .getSystemService(Context.WIFI_SERVICE); if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) { if (mSystemBroadcastReceiver == null) { mSystemBroadcastReceiver = new SystemBroadcastReceiver(wifiMgr); getActivity().registerReceiver(mSystemBroadcastReceiver, INTENT_FILTER_SCAN_AVAILABLE); } if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (wifiMgr.getScanResults() == null || wifiMgr.getScanResults().size() != mLastScanSize) { mLastScanSize = wifiMgr.getScanResults().size(); wifiMgr.startScan(); } } Map<String, String> wifiListStr = new LinkedHashMap<String, String>(); try { DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo(); wifiListStr.put("DNS1", Formatter.formatIpAddress(dhcpInfo.dns1)); wifiListStr.put("DNS2", Formatter.formatIpAddress(dhcpInfo.dns2)); wifiListStr.put("Default Gateway", Formatter.formatIpAddress(dhcpInfo.gateway)); wifiListStr.put("IP Address", Formatter.formatIpAddress(dhcpInfo.ipAddress)); wifiListStr.put("Subnet Mask", Formatter.formatIpAddress(dhcpInfo.netmask)); wifiListStr.put("Server IP", Formatter.formatIpAddress(dhcpInfo.serverAddress)); wifiListStr.put("Lease Time(sec)", String.valueOf(dhcpInfo.leaseDuration)); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); if (wifiInfo != null) { wifiListStr.put("LinkSpeed Mbps", String.valueOf(wifiInfo.getLinkSpeed())); int numberOfLevels = 10; int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1); wifiListStr.put("Signal%", String.valueOf(100 * level / numberOfLevels)); if (Build.VERSION.SDK_INT >= 23) { wifiListStr.put("MAC", getMacAddr()); } else { wifiListStr.put("MAC", wifiInfo.getMacAddress()); } } } catch (Exception ex) { m_log.e("Wifi %s", ex.getMessage()); } if (!wifiListStr.isEmpty()) { addBuild("WiFi...", wifiListStr); } try { if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { List<ScanResult> listWifi = wifiMgr.getScanResults(); if (listWifi != null && !listWifi.isEmpty()) { int idx = 0; for (ScanResult scanResult : listWifi) { Map<String, String> wifiScanListStr = new LinkedHashMap<String, String>(); wifiScanListStr.put("SSID", scanResult.SSID); if (Build.VERSION.SDK_INT >= 23) { wifiScanListStr.put(" Name", scanResult.operatorFriendlyName.toString()); wifiScanListStr.put(" Venue", scanResult.venueName.toString()); } // wifiScanListStr.put(" BSSID ",scanResult.BSSID); wifiScanListStr.put(" Capabilities", scanResult.capabilities); // wifiScanListStr.put(" Center Freq", String.valueOf(scanResult.centerFreq0)); // wifiScanListStr.put(" Freq width", String.valueOf(scanResult.channelWidth)); wifiScanListStr.put(" Level, Freq", String.format("%d, %d", scanResult.level, scanResult.frequency)); if (Build.VERSION.SDK_INT >= 17) { Date wifiTime = new Date(scanResult.timestamp); wifiScanListStr.put(" Time", wifiTime.toLocaleString()); } addBuild(String.format("WiFiScan #%d", ++idx), wifiScanListStr); } } } } catch (Exception ex) { m_log.e("WifiList %s", ex.getMessage()); } try { List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks(); for (WifiConfiguration wifiCfg : listWifiCfg) { Map<String, String> wifiCfgListStr = new LinkedHashMap<String, String>(); if (Build.VERSION.SDK_INT >= 23) { wifiCfgListStr.put("Name", wifiCfg.providerFriendlyName); } wifiCfgListStr.put("SSID", wifiCfg.SSID); String netStatus = ""; switch (wifiCfg.status) { case WifiConfiguration.Status.CURRENT: netStatus = "Connected"; break; case WifiConfiguration.Status.DISABLED: netStatus = "Disabled"; break; case WifiConfiguration.Status.ENABLED: netStatus = "Enabled"; break; } wifiCfgListStr.put(" Status", netStatus); wifiCfgListStr.put(" Priority", String.valueOf(wifiCfg.priority)); if (null != wifiCfg.wepKeys) { // wifiCfgListStr.put(" wepKeys", TextUtils.join(",", wifiCfg.wepKeys)); } String protocols = ""; if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.RSN)) protocols = "RSN "; if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.WPA)) protocols = protocols + "WPA "; wifiCfgListStr.put(" Protocols", protocols); String keyProt = ""; if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) keyProt = "none"; if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)) keyProt = "WPA+EAP "; if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) keyProt = "WPA+PSK "; wifiCfgListStr.put(" Keys", keyProt); if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) { // Remove network connections with no Password. // wifiMgr.removeNetwork(wifiCfg.networkId); } addBuild("WiFiCfg #" + wifiCfg.networkId, wifiCfgListStr); } } catch (Exception ex) { m_log.e("Wifi Cfg List %s", ex.getMessage()); } } if (expandAll) { // updateList(); int count = m_list.size(); for (int position = 0; position < count; position++) m_listView.expandGroup(position); } m_adapter.notifyDataSetChanged(); }
From source file:com.limegroup.gnutella.gui.DaapManager.java
/** * Starts the DAAP Server//from w w w .ja v a 2s . c o m */ public synchronized void start() throws IOException { if (!isServerRunning()) { try { InetAddress addr = InetAddress.getLocalHost(); if (addr.isLoopbackAddress() || !(addr instanceof Inet4Address)) { addr = null; Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces != null) { while (addr == null && interfaces.hasMoreElements()) { NetworkInterface nif = (NetworkInterface) interfaces.nextElement(); Enumeration addresses = nif.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = (InetAddress) addresses.nextElement(); if (!address.isLoopbackAddress() && address instanceof Inet4Address) { addr = address; break; } } } } } if (addr == null) { stop(); // No valid IP address -- just ignore, since // it's probably the user isn't connected to the // internet. Next time they start, it might work. return; } rendezvous = new RendezvousService(addr); map = new SongURNMap(); maxPlaylistSize = DaapSettings.DAAP_MAX_LIBRARY_SIZE.getValue(); String name = DaapSettings.DAAP_LIBRARY_NAME.getValue(); int revisions = DaapSettings.DAAP_LIBRARY_REVISIONS.getValue(); boolean useLibraryGC = DaapSettings.DAAP_LIBRARY_GC.getValue(); library = new Library(name, revisions, useLibraryGC); database = new Database(name); whatsNew = new Playlist(GUIMediator.getStringResource("SEARCH_TYPE_WHATSNEW")); creativecommons = new Playlist(GUIMediator.getStringResource("LICENSE_CC")); videos = new Playlist(GUIMediator.getStringResource("MEDIA_VIDEO")); Transaction txn = library.open(false); library.add(txn, database); database.add(txn, creativecommons); database.add(txn, whatsNew); database.add(txn, videos); creativecommons.setSmartPlaylist(txn, true); whatsNew.setSmartPlaylist(txn, true); videos.setSmartPlaylist(txn, true); txn.commit(); LimeConfig config = new LimeConfig(addr); final boolean NIO = DaapSettings.DAAP_USE_NIO.getValue(); server = DaapServerFactory.createServer(library, config, NIO); server.setAuthenticator(new LimeAuthenticator()); server.setStreamSource(new LimeStreamSource()); server.setFilter(new LimeFilter()); if (!NIO) { server.setThreadFactory(new LimeThreadFactory()); } final int maxAttempts = 10; for (int i = 0; i < maxAttempts; i++) { try { server.bind(); break; } catch (BindException bindErr) { if (i < (maxAttempts - 1)) { // try next port... config.nextPort(); } else { throw bindErr; } } } Thread serverThread = new ManagedThread(server, "DaapServerThread") { protected void managedRun() { try { super.managedRun(); } catch (Throwable t) { DaapManager.this.stop(); if (!handleError(t)) { GUIMediator.showError("ERROR_DAAP_RUN_ERROR"); DaapSettings.DAAP_ENABLED.setValue(false); if (t instanceof RuntimeException) throw (RuntimeException) t; throw new RuntimeException(t); } } } }; serverThread.setDaemon(true); serverThread.start(); rendezvous.registerService(); } catch (IOException err) { stop(); throw err; } } }