Java Code Examples for java.util.UUID#equals()

The following examples show how to use java.util.UUID#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UUIDUserType.java    From webdsl with Apache License 2.0 6 votes vote down vote up
public boolean equals (Object x, Object y) throws HibernateException
{
	if (x == y)
		return true ;

	if(x == null  ||  y == null)
		return false;

	if (!UUID.class.isAssignableFrom (x.getClass ()))
	{
		throw new HibernateException (x.getClass ().toString () + CAST_EXCEPTION_TEXT) ;
	}
	else if (!UUID.class.isAssignableFrom (y.getClass ()))
	{

		throw new HibernateException (y.getClass ().toString () + CAST_EXCEPTION_TEXT) ;
	}

	UUID a = (UUID) x ;
	UUID b = (UUID) y ;

	return a.equals (b) ;
}
 
Example 2
Source File: HookBSkyBlock.java    From CombatLogX with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doesTeamMatch(Player player1, Player player2) {
    if(player1 == null || player2 == null) return false;

    World world1 = player1.getWorld();
    World world2 = player2.getWorld();
    UUID worldId1 = world1.getUID();
    UUID worldId2 = world2.getUID();
    if(!worldId1.equals(worldId2)) return false;

    UUID uuid1 = player1.getUniqueId();
    UUID uuid2 = player2.getUniqueId();
    if(uuid1.equals(uuid2)) return true;

    Island island = getIslandFor(player1);
    ImmutableSet<UUID> memberSet = island.getMemberSet();
    return memberSet.contains(uuid2);
}
 
Example 3
Source File: HookFabledSkyBlock.java    From CombatLogX with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doesTeamMatch(Player player1, Player player2) {
    if(player1 == null || player2 == null) return false;

    UUID uuid1 = player1.getUniqueId();
    UUID uuid2 = player2.getUniqueId();
    if(uuid1.equals(uuid2)) return true;

    Island island1 = getIslandFor(player1);
    if(island1 == null) return false;

    Island island2 = getIslandFor(player2);
    if(island2 == null) return false;

    UUID islandId1 = island1.getIslandUUID();
    UUID islandId2 = island2.getIslandUUID();
    return islandId1.equals(islandId2);
}
 
Example 4
Source File: TapBluetoothManager.java    From tap-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
        public void onNotificationSubscribed(@NonNull String deviceAddress, @NonNull UUID characteristic) {
            if (characteristic.equals(TAP_DATA)) {
                log("Tap notification subscribed");
                notifyOnTapInputSubscribed(deviceAddress);
            } else if (characteristic.equals(MOUSE_DATA)) {
                log("Mouse notification subscribed");
                notifyOnMouseInputSubscribed(deviceAddress);
            } else if (characteristic.equals(AIR_MOUSE_DATA)) {
                log("Air mouse notification subscribed");
//                requestReadTapState(deviceAddress);
                notifyOnAirMouseDataSubscribed(deviceAddress);
            } else if (characteristic.equals(TX)) {
                log("Raw sensor notification subscribed");
                notifyOnRawSensorDataSubscribed(deviceAddress);
            }
        }
 
Example 5
Source File: PartyService.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public PartyMember getMemberById(final UUID id)
{
	for (PartyMember member : members)
	{
		if (id.equals(member.getMemberId()))
		{
			return member;
		}
	}

	return null;
}
 
Example 6
Source File: UserPreferencesImpl.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void doDelete(final String type, final String name, final UUID id)
{
    if (type == null && name != null)
    {
        throw new IllegalArgumentException("Cannot specify name without specifying type");
    }

    if (id != null)
    {
        final Set<Preference> allPreferences = doGetPreferences();
        for (Preference preference : allPreferences)
        {
            if (id.equals(preference.getId()))
            {
                if ((type == null || type.equals(preference.getType()))
                    && (name == null || name.equals(preference.getName())))
                {
                    doReplaceByTypeAndName(preference.getType(), preference.getName(), null);
                }
                break;
            }
        }
    }
    else
    {
        if (type != null && name != null)
        {
            doReplaceByTypeAndName(type, name, null);
        }
        else
        {
            doReplaceByType(type, Collections.<Preference>emptySet());
        }
    }
}
 
Example 7
Source File: BtBand.java    From sony-smartband-open-api with MIT License 5 votes vote down vote up
private void handleGenericAccessCallback( BluetoothGattCharacteristic characteristic ) {
    UUID uuid = characteristic.getUuid();

    if( uuid.equals( GenericAccessProfile.DEVICE_NAME_UUID ) ) {
        handleGADeviceName( characteristic );
    } else {
        Log.e( CLASS, "handleGenericAccessCallback: unknown response" );
    }
}
 
Example 8
Source File: PlayerJSONResolver.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean canAccess(Request request) {
    WebUser user = request.getUser().orElse(new WebUser(""));
    UUID playerUUID = identifiers.getPlayerUUID(request);
    UUID webUserUUID = identifiers.getPlayerUUID(user.getName());
    boolean isOwnPage = playerUUID.equals(webUserUUID);
    return user.hasPermission("page.player.other") || (user.hasPermission("page.player.self") && isOwnPage);
}
 
Example 9
Source File: NovaGuildImpl.java    From NovaGuilds with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void addPlayer(NovaPlayer nPlayer) {
	if(nPlayer == null) {
		LoggerUtils.info("Tried to add null player to a guild! " + name);
		return;
	}

	if(!players.contains(nPlayer)) {
		players.add(nPlayer);
		nPlayer.setGuild(this);

		if(getLeaderName() != null) {
			try {
				UUID leaderUUID = UUID.fromString(getLeaderName());

				if(leaderUUID.equals(nPlayer.getUUID())) {
					setLeader(nPlayer);
					leaderName = null;
				}
			}
			catch(IllegalArgumentException e) {
				if(getLeaderName().equalsIgnoreCase(nPlayer.getName())) {
					setLeader(nPlayer);
					leaderName = null;
				}
			}
		}

		if(NovaGuilds.getInstance().getRankManager().isLoaded() && !nPlayer.isLeader()) {
			nPlayer.setGuildRank(getDefaultRank());
		}
	}
}
 
Example 10
Source File: RootResource.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private ApplicationResource appResourceFor( UUID applicationId ) throws Exception {
    if ( applicationId.equals( emf.getManagementAppId() ) ) {
        throw new UnauthorizedException();
    }

    return getSubResource( ApplicationResource.class ).init( applicationId );
}
 
Example 11
Source File: PlayerCache.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes any island associated with this player and generally cleans up
 * the player
 *
 * @param playerUUID - the player's UUID
 */
public void zeroPlayerData(UUID playerUUID) {
    addPlayer(playerUUID);
    // Remove and clean up any team players (if the asadmin delete command
    // was called this is needed)
    if (playerCache.get(playerUUID).inTeam()) {
        UUID leader = playerCache.get(playerUUID).getTeamLeader();
        // If they are the leader, dissolve the team
        if (leader != null) {
            if (leader.equals(playerUUID)) {
                for (UUID member : playerCache.get(leader).getMembers()) {
                    addPlayer(member);
                    playerCache.get(member).setLeaveTeam();
                }
            } else {
                // Just remove them from the team
                addPlayer(leader);
                playerCache.get(leader).removeMember(playerUUID);
                playerCache.get(leader).save(false);
            }
        }
    }
    playerCache.get(playerUUID).setLeaveTeam();
    playerCache.get(playerUUID).setHasIsland(false);
    playerCache.get(playerUUID).clearHomeLocations();
    playerCache.get(playerUUID).setIslandLocation(null);
    playerCache.get(playerUUID).setIslandLevel(0);
    playerCache.get(playerUUID).save(false); // Needed?
    plugin.getTopTen().topTenRemoveEntry(playerUUID);
}
 
Example 12
Source File: RoundRobinGlobalLoadBalancer.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Finds node by id. Returns null in case of absence of specified id in request topology.
 *
 * @param top Topology for current request.
 * @param foundNodeId Node id.
 * @return Found node or null in case of absence of specified id in request topology.
 */
private static ClusterNode findNodeById(Iterable<ClusterNode> top, UUID foundNodeId) {
    for (ClusterNode node : top)
        if (foundNodeId.equals(node.id()))
            return node;

    return null;
}
 
Example 13
Source File: PlayerDataMigrator.java    From GriefDefender with MIT License 4 votes vote down vote up
private static void migratePlayerData(World world) {
    Path path = null;
    if (world == null) {
        path = BaseStorage.globalPlayerDataPath;
    } else {
        path = BaseStorage.worldConfigMap.get(world.getUID()).getPath().getParent().resolve("PlayerData");
    }

    if (!path.toFile().exists()) {
        return;
    }
    if (path.resolve("_migrated").toFile().exists()) {
        return;
    }
    File[] files = path.toFile().listFiles();
    if (files != null) {
        GriefDefenderPlugin.getInstance().getLogger().info("Migrating " + files.length + " player data files...");
        for (int i = 0; i < files.length; i++) {
            final File file = files[i];
            if (file.getName().startsWith("_")) {
                continue;
            }
            GriefDefenderPlugin.getInstance().getLogger().info("Migrating playerdata " + file.getName() + "...");
            UUID uuid = null;
            try {
                uuid = UUID.fromString(file.getName().replaceFirst("[.][^.]+$", ""));
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                continue;
            }
            // ignore internal player uuid's
            if (uuid.equals(GriefDefenderPlugin.PUBLIC_UUID) || uuid.equals(GriefDefenderPlugin.ADMIN_USER_UUID) || uuid.equals(GriefDefenderPlugin.WORLD_USER_UUID)) {
                continue;
            }
            final PlayerStorageData playerStorage = createPlayerStorageData(world, uuid);
            if (playerStorage == null) {
                continue;
            }
            final GDPermissionUser user = PermissionHolderCache.getInstance().getOrCreateUser(uuid);
            final String accruedClaimBlocks = String.valueOf(playerStorage.getConfig().getAccruedClaimBlocks());
            final String bonusClaimBlocks = String.valueOf(playerStorage.getConfig().getBonusClaimBlocks());
            final Set<Context> contexts = new HashSet<>();
            if (world != null) {
                contexts.add(new Context("server", PermissionUtil.getInstance().getServerName()));
                contexts.add(new Context("world", world.getName().toLowerCase()));
            } else {
                final String contextType = GriefDefenderPlugin.getGlobalConfig().getConfig().playerdata.contextType;
                if (contextType.equalsIgnoreCase("world")) {
                    // ignore
                } else if (contextType.equalsIgnoreCase("global")) {
                    contexts.add(new Context("server", "global"));
                } else {
                    contexts.add(new Context("server", PermissionUtil.getInstance().getServerName()));
                }
            }
            GriefDefenderPlugin.getInstance().getPermissionProvider().setOptionValue(user, Options.ACCRUED_BLOCKS.getPermission(), accruedClaimBlocks, contexts);
            GriefDefenderPlugin.getInstance().getPermissionProvider().setOptionValue(user, Options.BONUS_BLOCKS.getPermission(), bonusClaimBlocks, contexts);
            count++;
        }
    }
}
 
Example 14
Source File: BaseChangePinRESTHandler.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public void assertValidRequest(FullHttpRequest req, ChannelHandlerContext ctx) {
   String json = req.content().toString(CharsetUtil.UTF_8);
   ClientMessage clientMessage = JSON.fromJson(json, ClientMessage.class);
   
   String destination = clientMessage.getDestination();
   // FIXME really annoying that we have to load person twice, but would require a pretty major API shift in RESTHandler to fix this
   Person person = loadPerson(destination);
   PinErrors.assertPersonFound(person);
   
   String pin = extractPin(clientMessage);
   String place = extractPlaceId(clientMessage, person);

   // Validate the request
   Errors.assertRequiredParam(pin, PersonCapability.VerifyPinRequest.ATTR_PIN);
   Errors.assertRequiredParam(place, PersonCapability.VerifyPinRequest.ATTR_PLACE);
   Errors.assertValidRequest(pin.length() == 4 && StringUtils.isNumeric(pin), "pin must be 4 numerical digits");
   
   Client client = clientFactory.get(ctx.channel());
   
   /* Validate the creds and auth */
   UUID placeID = UUID.fromString(place);

   Address dst = Address.fromString(destination);
   
   List<AuthorizationGrant> grants = authGrantDao.findForEntity(person.getId());
   
   if(checkPrincipal) {
      AuthorizationContext authCtx = client.getAuthorizationContext();
      if(permissionsEmpty(authCtx.getInstancePermissions(placeID)) && permissionsEmpty(authCtx.getNonInstancePermissions(placeID))) {
         throw new UnauthorizedRequestException(dst, "Unauthorized");
      }

      UUID loggedInPerson = client.getPrincipalId();
      if(!loggedInPerson.equals(person.getId()) && person.getHasLogin()) {
         throw new UnauthorizedRequestException(dst, "Unauthorized request, requester must be logged in as the person that the pin is being verified for");
      }
   }

   if(!grants.stream().anyMatch((a) -> { return a.getPlaceId().equals(placeID); })) {
      throw new UnauthorizedRequestException(dst, "Unauthorized");
   }
}
 
Example 15
Source File: GDClaim.java    From GriefDefender with MIT License 4 votes vote down vote up
public ClaimResult changeType(ClaimType type, Optional<UUID> ownerUniqueId, CommandSource src) {
    if (type == this.type) {
        return new GDClaimResult(ClaimResultType.SUCCESS);
    }

    final Player sourcePlayer = src instanceof Player ? (Player) src : null;
    GDChangeClaimEvent.Type event = new GDChangeClaimEvent.Type(this, type);
    GriefDefender.getEventManager().post(event);
    if (event.cancelled()) {
        return new GDClaimResult(ClaimResultType.CLAIM_EVENT_CANCELLED, event.getMessage().orElse(null));
    }

    final GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(this.world.getUniqueId());
    final GDPlayerData sourcePlayerData = src != null && src instanceof Player ? claimWorldManager.getOrCreatePlayerData(((Player) src).getUniqueId()) : null;
    UUID newOwnerUUID = ownerUniqueId.orElse(this.ownerUniqueId);
    final ClaimResult result = this.validateClaimType(type, newOwnerUUID, sourcePlayerData);
    if (!result.successful()) {
        return result;
    }

    if (type == ClaimTypes.ADMIN) {
        newOwnerUUID = GriefDefenderPlugin.ADMIN_USER_UUID;
    }

    final String fileName = this.getClaimStorage().filePath.getFileName().toString();
    final Path newPath = this.getClaimStorage().folderPath.getParent().resolve(type.getName().toLowerCase()).resolve(fileName);
    try {
        if (Files.notExists(newPath.getParent())) {
            Files.createDirectories(newPath.getParent());
        }
        Files.move(this.getClaimStorage().filePath, newPath);
        if (type == ClaimTypes.TOWN) {
            this.setClaimStorage(new TownStorageData(newPath, this.getWorldUniqueId(), newOwnerUUID, this.cuboid));
        } else {
            this.setClaimStorage(new ClaimStorageData(newPath, this.getWorldUniqueId(), (ClaimDataConfig) this.getInternalClaimData()));
        }
        this.claimData = this.claimStorage.getConfig();
        this.getClaimStorage().save();
    } catch (IOException e) {
        e.printStackTrace();
        return new GDClaimResult(ClaimResultType.CLAIM_NOT_FOUND, TextComponent.of(e.getMessage()));
    }

    // If switched to admin or new owner, remove from player claim list
    if (type == ClaimTypes.ADMIN || (this.ownerUniqueId != null && !this.ownerUniqueId.equals(newOwnerUUID))) {
        final Set<Claim> currentPlayerClaims = claimWorldManager.getInternalPlayerClaims(this.ownerUniqueId);
        if (currentPlayerClaims != null) {
            currentPlayerClaims.remove(this);
        }
    }
    if (type != ClaimTypes.ADMIN) {
        final Set<Claim> newPlayerClaims = claimWorldManager.getInternalPlayerClaims(newOwnerUUID);
        if (newPlayerClaims != null && !newPlayerClaims.contains(this)) {
            newPlayerClaims.add(this);
        }
    }

    if (!this.isAdminClaim() && this.ownerPlayerData != null) {
        final Player player = Sponge.getServer().getPlayer(this.ownerUniqueId).orElse(null);
        if (player != null) {
            this.ownerPlayerData.revertClaimVisual(this);
        }
    }

    // revert visuals for all players watching this claim
    List<UUID> playersWatching = new ArrayList<>(this.playersWatching);
    for (UUID playerUniqueId : playersWatching) {
        final Player spongePlayer = Sponge.getServer().getPlayer(playerUniqueId).orElse(null);
        final GDPlayerData playerData = claimWorldManager.getOrCreatePlayerData(playerUniqueId);
        if (spongePlayer != null) {
            playerData.revertClaimVisual(this);
        }
    }

    if (!newOwnerUUID.equals(GriefDefenderPlugin.ADMIN_USER_UUID)) {
        this.setOwnerUniqueId(newOwnerUUID);
    }
    this.setType(type);
    this.claimVisual = null;
    this.getInternalClaimData().setRequiresSave(true);
    this.getClaimStorage().save();
    return new GDClaimResult(ClaimResultType.SUCCESS);
}
 
Example 16
Source File: ModuleExtract.java    From Logistics-Pipes-2 with MIT License 4 votes vote down vote up
@Override
public boolean execute(TileRoutedPipe te) {
	if(ticksTillOp!=0) {
		ticksTillOp-=1;
	}else {
		
		ticksTillOp=References.MOD_BASE_OPERATION_RATE;
		if(te.hasInventory() && te.hasNetwork()) {
			boolean hasWorked = false;
			int tryDest = 0;
			int tryItem = 0;
			ArrayList<ItemStack> stacks = te.getItemsInInventory(te.getNetwork().getDirectionForDestination(te.nodeID));
			try {
				if(!stacks.isEmpty()) {
					Item item = stacks.get(tryItem).getItem();
					while(!te.getNetwork().hasStorageForItem(item) && tryItem<stacks.size()) {
						tryItem+=1;
						item = stacks.get(tryItem).getItem();
						LogisticsPipes2.logger.log(Level.INFO, "Module:" + this.MODULE_ID + " has skipped an Itemstack!");
					}
					UUID nodeT = te.getNetwork().getClosestStorageNode(item, te.nodeID, tryDest);
					while(!hasWorked) {
						if(nodeT==null) {
							return false;
						}
						if(nodeT.equals(te.nodeID)) {
							tryDest+=1;
							nodeT = te.getNetwork().getClosestStorageNode(item, te.nodeID, tryDest);
							LogisticsPipes2.logger.log(Level.INFO, "Module:" + this.MODULE_ID + " avoided Self-Routing!");
							continue;
						}
						
						ItemStack stack = stacks.get(tryItem).copy();
						if(stack.getCount()>References.MOD_EXTRACT_BASE_COUNT) {
							stack.setCount(References.MOD_EXTRACT_BASE_COUNT);
						}
						te.routeItemTo(nodeT, stack);
						hasWorked=true;
					}
				}
			} catch (Exception e) {
				return false;
			}
		}
	}
	
	return true;
}
 
Example 17
Source File: CoopPlay.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Adds a player to an island as a coop player.
 * 
 * @param requester - coop requester
 * @param newPlayer - new player to add to the coop
 * @return true if successful, otherwise false
 */
public boolean addCoopPlayer(Player requester, Player newPlayer) {
    // plugin.getLogger().info("DEBUG: adding coop player");
    // Find out which island this coop player is being requested to join
    Location islandLoc = null;
    if (plugin.getPlayers().inTeam(requester.getUniqueId())) {
        islandLoc = plugin.getPlayers().getTeamIslandLocation(requester.getUniqueId());
        // Tell the team owner
        UUID leaderUUID = plugin.getPlayers().getTeamLeader(requester.getUniqueId());
        // Check if only leader can coop
        if(Settings.onlyLeaderCanCoop && (!requester.getUniqueId().equals(leaderUUID))){
            Util.sendMessage(requester, ChatColor.RED + plugin.myLocale(requester.getUniqueId()).cannotCoop);
        	return false;
        }
        // Tell all the team members
        for (UUID member : plugin.getPlayers().getMembers(leaderUUID)) {
            // plugin.getLogger().info("DEBUG: " + member.toString());
            if (!member.equals(requester.getUniqueId())) {
                Player player = plugin.getServer().getPlayer(member);
                if (player != null) {
                    Util.sendMessage(player, ChatColor.GOLD
                            + plugin.myLocale(player.getUniqueId()).coopInvited.replace("[name]", requester.getName()).replace("[player]", newPlayer.getName()));
                    Util.sendMessage(player, ChatColor.GOLD + plugin.myLocale(player.getUniqueId()).coopUseExpel);
                } else {
                    if (member.equals(leaderUUID)) {
                        // offline - tell leader
                        plugin.getMessages().setMessage(leaderUUID,
                                plugin.myLocale(leaderUUID).coopInvited.replace("[name]", requester.getName()).replace("[player]", newPlayer.getName()));
                    }
                }
            }
        }
    } else {
        islandLoc = plugin.getPlayers().getIslandLocation(requester.getUniqueId());
    }
    Island coopIsland = plugin.getGrid().getIslandAt(islandLoc);
    if (coopIsland == null) {
        return false;
    }
    // Fire event and check if it is cancelled
    final CoopJoinEvent event = new CoopJoinEvent(newPlayer.getUniqueId(), coopIsland, requester.getUniqueId());
    plugin.getServer().getPluginManager().callEvent(event);
    if (event.isCancelled()) {
        return false;
    }
    // Add the coop to the list. If the location already exists then the new
    // requester will replace the old
    if (coopPlayers.containsKey(newPlayer.getUniqueId())) {
        // This is an existing player in the list
        // Add this island to the set
        coopPlayers.get(newPlayer.getUniqueId()).put(coopIsland.getCenter(), requester.getUniqueId());
    } else {
        // First time. Create the hashmap
        HashMap<Location, UUID> loc = new HashMap<>();
        loc.put(coopIsland.getCenter(), requester.getUniqueId());
        coopPlayers.put(newPlayer.getUniqueId(), loc);
    }
    return true;
}
 
Example 18
Source File: EmbeddedLeaderService.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Override
public boolean hasLeadership(@Nonnull UUID leaderSessionId) {
	return isLeader && leaderSessionId.equals(currentLeaderSessionId);
}
 
Example 19
Source File: ClientImpl.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public boolean pingNode(@NotNull final UUID nodeId) {
    if (nodeId.equals(getLocalNodeId()))
        return true;

    TcpDiscoveryNode node = rmtNodes.get(nodeId);

    if (node == null || !node.visible())
        return false;

    GridFutureAdapter<Boolean> fut = pingFuts.get(nodeId);

    if (fut == null) {
        fut = new GridFutureAdapter<>();

        GridFutureAdapter<Boolean> oldFut = pingFuts.putIfAbsent(nodeId, fut);

        if (oldFut != null)
            fut = oldFut;
        else {
            State state = this.state;

            if (spi.getSpiContext().isStopping() || state == STOPPED || state == SEGMENTED) {
                if (pingFuts.remove(nodeId, fut))
                    fut.onDone(false);

                return false;
            }
            else if (state == DISCONNECTED) {
                if (pingFuts.remove(nodeId, fut))
                    fut.onDone(new IgniteClientDisconnectedCheckedException(null,
                        "Failed to ping node, client node disconnected."));
            }
            else {
                final GridFutureAdapter<Boolean> finalFut = fut;

                timer.schedule(new TimerTask() {
                    @Override public void run() {
                        if (pingFuts.remove(nodeId, finalFut)) {
                            if (ClientImpl.this.state == DISCONNECTED)
                                finalFut.onDone(new IgniteClientDisconnectedCheckedException(null,
                                    "Failed to ping node, client node disconnected."));
                            else
                                finalFut.onDone(false);
                        }
                    }
                }, spi.netTimeout);

                sockWriter.sendMessage(new TcpDiscoveryClientPingRequest(getLocalNodeId(), nodeId));
            }
        }
    }

    try {
        return fut.get();
    }
    catch (IgniteInterruptedCheckedException ignored) {
        return false;
    }
    catch (IgniteCheckedException e) {
        throw new IgniteSpiException(e);
    }
}
 
Example 20
Source File: AbstractQuorum.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
         * Method is invoked by the {@link QuorumWatcher} when a joined service
         * leaves the quorum and updates the internal state of the quorum to
         * reflect that state change.
         * 
         * @param serviceId
         *            The service {@link UUID}.
         */
        protected void serviceLeave(final UUID serviceId) {
            if (serviceId == null)
                throw new IllegalArgumentException();
            lock.lock();
            try {
                // #of joined services _before_ the service leaves.
                final int njoinedBefore = joined.size();
                // The serviceId of the 1st joined service (and the leader iff
                // the quorum is met).
                final UUID leaderId;
                {
                    final Iterator<UUID> itr = joined.iterator();
                    leaderId = itr.hasNext() ? itr.next() : null;
                }
                if (!joined.remove(serviceId)) {
                    // This service was not joined.
                    return;
                }
                joinedChange.signalAll();
                final int k = replicationFactor();
                // iff the quorum was joined.
                final boolean wasJoined = njoinedBefore >= kmeet;
                // iff the leader just left the quorum.
                final boolean leaderLeft = wasJoined
                        && serviceId.equals(leaderId);
                // iff the quorum will break.
                final boolean willBreak = leaderLeft
                        || (njoinedBefore == kmeet);
                if (log.isInfoEnabled())
                    log.info("serviceId=" + serviceId + ", k=" + k
                            + ", njoined(before)=" + njoinedBefore + ", wasJoined="
                            + wasJoined + ", leaderLeft=" + leaderLeft
                            + ", willBreak=" + willBreak);
                final QuorumMember<S> client = getClientAsMember();
                if (client != null && willBreak) {
                    /*
                     * Invalidate the current quorum token.
                     * 
                     * Note: Only clients can take actions on the distributed
                     * quorum state. Non-clients monitoring the quorum will have
                     * to wait until their watcher notices that the quorum token
                     * in the distributed quorum state has been cleared.
                     * 
                     * Note: Services which are members of the quorum will see
                     * the quorumBreak() message. They MUST handle that message
                     * by (a) doing an abort() which will discard any buffered
                     * writes and reload their current root block; and (b) cast
                     * a vote for their current commit time. Once a consensus is
                     * reached on the current commit time, the services will
                     * join in the vote order, a new leader will be elected, and
                     * the quorum will meet again.
                     */
//                    new Thread() {public void run(){actor.clearToken();}}.start();
                    doAction(new Runnable() {public void run() {actor.clearToken();}});
                }
                if (client != null) {
                    // Notify all quorum members that a service left.
                    try {
                        /**
                         * PREVIOUSLY called client.serviceLeave()
                         * unconditionally
                         * 
                         * @see <a
                         *      href="https://sourceforge.net/apps/trac/bigdata/ticket/695">
                         *      HAJournalServer reports "follower" but is in
                         *      SeekConsensus and is not participating in
                         *      commits </a>
                         */
                        final UUID clientId = client.getServiceId();
                    	if (serviceId.equals(clientId))
                    			client.serviceLeave();
                    	
                    } catch (Throwable t) {
                        launderThrowable(t);
                    }
                }
                sendEvent(new E(QuorumEventEnum.SERVICE_LEAVE, lastValidToken,
                        token, serviceId));
//                if (client != null && leaderLeft) {
//                    // Notify all quorum members that the leader left.
//                    client.leaderLeft();
//                }
//                if (leaderLeft) {
//                    sendEvent(new E(QuorumEventEnum.LEADER_LEFT, token(),
//                            serviceId));
//                }
            } finally {
                lock.unlock();
            }
        }