java.util.UUID Java Examples

The following examples show how to use java.util.UUID. 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: TcpCommunicationSpiSkipMessageSendTest.java    From ignite with Apache License 2.0 8 votes vote down vote up
/**
 * Close communication clients. It will lead that sendMessage method will be trying to create new ones.
 */
private void closeTcpConnections() {
    final ConcurrentMap<UUID, GridCommunicationClient[]> clients = U.field(this, "clients");

    Set<UUID> ids = clients.keySet();

    if (!ids.isEmpty()) {
        log.info("Close TCP clients: " + ids);

        for (UUID nodeId : ids) {
            GridCommunicationClient[] clients0 = clients.remove(nodeId);

            if (clients0 != null) {
                for (GridCommunicationClient client : clients0) {
                    if (client != null)
                        client.forceClose();
                }
            }
        }

        log.info("TCP clients are closed.");
    }
}
 
Example #2
Source File: ListShardMap.java    From elastic-db-tools-for-java with MIT License 6 votes vote down vote up
/**
 * Gets all the mappings that exist for the given shard.
 *
 * @param shard
 *            Shard for which the mappings will be returned.
 * @param lookupOptions
 *            Whether to search in the cache and/or store.
 * @return Read-only collection of mappings that satisfy the given shard constraint.
 */
public List<PointMapping> getMappings(Shard shard,
        LookupOptions lookupOptions) {
    ExceptionUtils.disallowNullArgument(shard, "shard");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        log.info("GetPointMappings", "Start; Shard:{}; Lookup Options: {}", shard.getLocation(), lookupOptions);

        Stopwatch stopwatch = Stopwatch.createStarted();

        List<PointMapping> pointMappings = lsm.getMappingsForRange(null, shard, lookupOptions);

        stopwatch.stop();

        log.info("GetPointMappings", "Complete; Shard: {}; Lookup Options: {}; Duration:{}", shard.getLocation(), lookupOptions,
                stopwatch.elapsed(TimeUnit.MILLISECONDS));

        return pointMappings;
    }
}
 
Example #3
Source File: UpdateIpcdStateColumns.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void execute(ExecutionContext context, boolean autoRollback) throws CommandExecutionException {
   Session session = context.getSession();
   PreparedStatement update = session.prepare(UPDATE_STATES);

   BoundStatement select = session.prepare(SELECT).bind();
   select.setConsistencyLevel(ConsistencyLevel.ALL);
   ResultSet rs = context.getSession().execute(select);
   for(Row row: rs) {
      String protocolAddress = row.getString("protocoladdress");
      UUID placeId = row.getUUID("placeid");
      BoundStatement bs = new BoundStatement(update);
      bs.setString("connState", "ONLINE");
      bs.setString("registrationState", placeId == null ? "UNREGISTERED" : "REGISTERED");
      bs.setString("protocolAddress", protocolAddress);
      session.execute(bs);
   }
}
 
Example #4
Source File: GridDhtAtomicCache.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param nodeId Node ID.
 * @param checkReq Request.
 */
private void processCheckUpdateRequest(UUID nodeId, GridNearAtomicCheckUpdateRequest checkReq) {
    /*
     * Message is processed in the same stripe, so primary already processed update request. It is possible
     * response was not sent if operation result was empty. Near node will get original response or this one.
     */
    GridNearAtomicUpdateResponse res = new GridNearAtomicUpdateResponse(ctx.cacheId(),
        nodeId,
        checkReq.futureId(),
        checkReq.partition(),
        false,
        false);

    GridCacheReturn ret = new GridCacheReturn(false, true);

    res.returnValue(ret);

    sendNearUpdateReply(nodeId, res);
}
 
Example #5
Source File: TokenServiceTest.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeInvalidatedToken()
{
    ServiceResponse<String> response = _tokenService.generateToken(
            TokenService.Purpose.RESET_PASSWORD, _user, Duration.ofDays(1L));
    Assert.assertTrue(_tokenService.invalidateToken(response.getResult()).isOk());

    Assert.assertTrue(_tokenService.invalidateToken(null).getStatus() == ServiceResponse.Status.ERROR);

    Assert.assertTrue(_tokenService.invalidateToken(
            UUID.randomUUID().toString()).getStatus() == ServiceResponse.Status.ERROR);

    response = _tokenService.generateToken(
            TokenService.Purpose.RESET_PASSWORD, _user, Duration.ofDays(1L));
    _tokenService.invalidateToken(response.getResult());
    Assert.assertTrue(_tokenService.invalidateToken(response.getResult()).getStatus() == ServiceResponse.Status.ERROR);
}
 
Example #6
Source File: GlobalIndexUidAggregatorTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testEqualsMax() throws Exception {
    agg.reset();
    List<String> savedUUIDs = new ArrayList<>();
    Collection<Value> values = Lists.newArrayList();
    for (int i = 0; i < GlobalIndexUidAggregator.MAX; i++) {
        Builder b = createNewUidList();
        b.setIGNORE(false);
        String uuid = UUID.randomUUID().toString();
        savedUUIDs.add(uuid);
        b.setCOUNT(1);
        b.addUID(uuid);
        Uid.List uidList = b.build();
        Value val = new Value(uidList.toByteArray());
        values.add(val);
    }
    Value result = agg.reduce(new Key("key"), values.iterator());
    Uid.List resultList = Uid.List.parseFrom(result.get());
    assertNotNull(resultList);
    assertEquals(false, resultList.getIGNORE());
    assertEquals(resultList.getUIDCount(), (GlobalIndexUidAggregator.MAX));
    List<String> resultListUUIDs = resultList.getUIDList();
    for (String s : savedUUIDs)
        assertTrue(resultListUUIDs.contains(s));
}
 
Example #7
Source File: TSSmsServiceImpl.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
* 替换sql中的变量
* @param sql
* @return
*/
public String replaceVal(String sql,TSSmsEntity t){
	sql  = sql.replace("#{id}",String.valueOf(t.getId()));
	sql  = sql.replace("#{create_name}",String.valueOf(t.getCreateName()));
	sql  = sql.replace("#{create_by}",String.valueOf(t.getCreateBy()));
	sql  = sql.replace("#{create_date}",String.valueOf(t.getCreateDate()));
	sql  = sql.replace("#{update_name}",String.valueOf(t.getUpdateName()));
	sql  = sql.replace("#{update_by}",String.valueOf(t.getUpdateBy()));
	sql  = sql.replace("#{update_date}",String.valueOf(t.getUpdateDate()));
	sql  = sql.replace("#{es_title}",String.valueOf(t.getEsTitle()));
	sql  = sql.replace("#{es_type}",String.valueOf(t.getEsType()));
	sql  = sql.replace("#{es_sender}",String.valueOf(t.getEsSender()));
	sql  = sql.replace("#{es_receiver}",String.valueOf(t.getEsReceiver()));
	sql  = sql.replace("#{es_content}",String.valueOf(t.getEsContent()));
	sql  = sql.replace("#{es_sendtime}",String.valueOf(t.getEsSendtime()));
	sql  = sql.replace("#{es_status}",String.valueOf(t.getEsStatus()));
	sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
	return sql;
}
 
Example #8
Source File: DefaultErrorDTOTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "NULL",
    "EMPTY",
    "NOT_EMPTY"
}, splitBy = "\\|")
@Test
public void constructor_with_Error_object_arg_should_pull_values_from_Error_object(MetadataArgOption metadataArgOption) {
    // given
    DefaultErrorDTO copyError = new DefaultErrorDTO(UUID.randomUUID().toString(), UUID.randomUUID().toString(), generateMetadata(metadataArgOption));

    // when
    DefaultErrorDTO error = new DefaultErrorDTO(copyError);

    // then
    assertThat(error.code).isEqualTo(copyError.code);
    assertThat(error.message).isEqualTo(copyError.message);
    verifyMetadata(error, metadataArgOption, copyError.metadata);
}
 
Example #9
Source File: CamelFtpBaseTest.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
/**
 * Start the FTP server, create & clean home directory
 */
@Before
public void initialize() throws FtpException, IOException {
    File tempDir = new File(System.getProperty("java.io.tmpdir"));
    ftpRoot = new File(tempDir,
                       "ftp");

    if (ftpRoot.exists()) {
        FileUtils.deleteDirectory(ftpRoot);
    }

    boolean created = ftpRoot.mkdir();
    if (!created) {
        throw new IllegalArgumentException("FTP root directory has not been created, " + "check system property java.io.tmpdir");
    }
    String fileName = "test_file_" + CamelFtpTest.class.getName() + "_" + UUID.randomUUID().toString();

    File testDir = new File(ftpRoot,
                            "testDirectory");
    testFile = new File(testDir,
                        fileName);

    server = configureFtpServer(new FtpServerBuilder());
    server.start();
}
 
Example #10
Source File: HereAccountTokenScopeTest.java    From here-aaa-java-sdk with Apache License 2.0 6 votes vote down vote up
private ClientAuthorizationRequestProvider getClientAuthorizationRequestProvider() throws Exception {
    String prefix = UUID.randomUUID().toString();
    File file = File.createTempFile(prefix, null);
    file.deleteOnExit();

    byte[] bytes = ("here.token.endpoint.url="+url+"\n"
            + "here.client.id="+clientId+"\n"
            + "here.access.key.id="+accessKeyId+"\n"
            + "here.access.key.secret="+accessKeySecret+"\n"
            + "here.token.scope="+TEST_PROJECT)
            .getBytes(StandardCharsets.UTF_8);
    try (FileOutputStream outputStream = new FileOutputStream(file)) {
        outputStream.write(bytes);
        outputStream.flush();
    }

    return new FromDefaultHereCredentialsPropertiesFile(file);
}
 
Example #11
Source File: TestBucketingProjection.java    From iceberg with Apache License 2.0 6 votes vote down vote up
@Test
public void testBucketUUIDInclusive() {
  UUID value = new UUID(123L, 456L);
  Schema schema = new Schema(optional(1, "value", Types.UUIDType.get()));
  PartitionSpec spec = PartitionSpec.builderFor(schema).bucket("value", 10).build();

  // the bucket number of the value (i.e. UUID(123L, 456L)) is 4
  assertProjectionInclusive(spec, equal("value", value), Expression.Operation.EQ, "4");
  assertProjectionInclusiveValue(spec, notEqual("value", value), Expression.Operation.TRUE);
  assertProjectionInclusiveValue(spec, lessThan("value", value), Expression.Operation.TRUE);
  assertProjectionInclusiveValue(spec, lessThanOrEqual("value", value), Expression.Operation.TRUE);
  assertProjectionInclusiveValue(spec, greaterThan("value", value), Expression.Operation.TRUE);
  assertProjectionInclusiveValue(spec, greaterThanOrEqual("value", value), Expression.Operation.TRUE);

  UUID anotherValue = new UUID(456L, 123L);
  assertProjectionInclusive(spec, in("value", value, anotherValue),
      Expression.Operation.IN, "[4, 6]");
  assertProjectionInclusiveValue(spec, notIn("value", value, anotherValue), Expression.Operation.TRUE);
}
 
Example #12
Source File: FileUtils.java    From ywh-frame with GNU General Public License v3.0 5 votes vote down vote up
public static String[] uploadFile(MultipartFile file){
    log.info("成功获取文件");
    //获取文件名
    String fileName = file.getOriginalFilename();
    String separator = "/";
    String[] suffixName = {".jpg",".png",".mp3"};
    //判断类型
    String type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf("."), fileName.length()):"";
    log.info("文件初始名称为:" + fileName + " 类型为:" + type);
    // 2. 使用随机生成的字符串+源图片扩展名组成新的图片名称,防止图片重名
    String newfileName = UUID.randomUUID().toString().replaceAll("-","") + fileName.substring(fileName.lastIndexOf("."));
    //存放磁盘的路径以及判断有没有
    String suffix = "//" + Calendar.getInstance().get(Calendar.YEAR) + "-" + (Calendar.getInstance().get(Calendar.MONTH) + 1);
    File filePath = suffixName[2].equals(type)? new File(SAVE_PATH + "//data//" +"image" + suffix): new File(SAVE_PATH + "//data//" +"audio" + suffix);
    if (!filePath.exists() && !filePath.isDirectory()) {
        if (separator.equals(File.separator)) {
            log.info("Liunx下创建");
            filePath.setWritable(true, false);
            filePath.mkdirs();
        } else {
            log.info("windows下创建");
            filePath.mkdirs();
        }
    }
    //transferto()方法,是springmvc封装的方法,用于图片上传时,把内存中图片写入磁盘
    log.info("存储地址:" + filePath.getPath());
    try {
        file.transferTo(new File(filePath.getPath()+ "//" + newfileName));
        String[] response= new String[2];
        response[0] = filePath.getPath()+ "//" + newfileName;
        response[1] = type;
        return response;
    } catch (IOException e) {
        e.printStackTrace();
        throw MyExceptionUtil.mxe("上传文件失败!",e);
    }
}
 
Example #13
Source File: PlayerContext.java    From ChatUI with MIT License 5 votes vote down vote up
private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) {
    this.playerUUID = playerUuid;
    this.width = width;
    this.height = height;
    this.forceUnicode = forceUnicode;
    this.utils = utils;
}
 
Example #14
Source File: MessageQueueHandler.java    From Okra with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, O msg) throws Exception {
    UUID uuid = CHANNEL_UUID.get(ctx.channel());
    if (null != uuid) {
        Session session = SESSIONS.get(uuid);
        if (null != session) {
            this.processor.addRequest(newExecutor(session, msg));
        }
    }
}
 
Example #15
Source File: TinkerPopOperations.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private static Optional<RelationType> getRelationDescription(GraphTraversalSource traversal, UUID typeId) {
  return getFirst(traversal
    .V()
    //.has(T.label, LabelP.of("relationtype"))
    .has("tim_id", typeId.toString())
  )
    .map(RelationType::relationType);
}
 
Example #16
Source File: UDDIInquiryJAXRSTest.java    From juddi with Apache License 2.0 5 votes vote down vote up
@Test(expected = WebApplicationException.class)
public void testGetEndpointsByServiceXML_NULL() {
        System.out.println("getEndpointsByServiceXML_NULL");
        String id = UUID.randomUUID().toString();

        UriContainer expResult = null;
        UriContainer result = instance.getEndpointsByServiceXML(id);

}
 
Example #17
Source File: ProtoUtil.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
public static Cmmn.UUID convert(UUID uuid) {
    return Cmmn.UUID
        .newBuilder()
        .setMsb(uuid.getMostSignificantBits())
        .setLsb(uuid.getLeastSignificantBits())
        .build();
}
 
Example #18
Source File: ActorTimerExecuterService.java    From actor4j-core with Apache License 2.0 5 votes vote down vote up
@Override
public ScheduledFuture<?> schedule(final ActorMessage<?> message, final UUID dest, long initalDelay, long period, TimeUnit unit) {
	return schedule(new Supplier<ActorMessage<?>>() {
		@Override
		public ActorMessage<?> get() {
			return message;
		}
	}, dest, initalDelay, period, unit);
}
 
Example #19
Source File: DefaultPlaceExecutorFactory.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public PlaceEnvironmentExecutor load(UUID placeId) {
   RuleEnvironment environment = ruleEnvDao.findByPlace(placeId);
   if(environment == null) {
      return null;
   }
   if(environment.getRules() == null || environment.getRules().isEmpty()) {
      return new InactivePlaceExecutor(() -> this.doLoad(placeId), placeId);
   }
   else {
      return this.doLoad(placeId);
   }
}
 
Example #20
Source File: PublishedBlogResourceTest.java    From ddd-architecture-samples with MIT License 5 votes vote down vote up
@Test
void should_return_409_when_no_need_to_publish() {
    UUID createdBlogId = createBlogAndGetId("Test Blog", "Something...", authorId);

    publishBlog(createdBlogId);

    publishBlog(createdBlogId)
            .then()
            .spec(CONFLICT_SPEC)
            .body("message", is("no need to publish"));
}
 
Example #21
Source File: OfflineLicenseHelper.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs an instance. Call {@link #release()} when the instance is no longer required.
 *
 * @param uuid The UUID of the drm scheme.
 * @param mediaDrm An underlying {@link ExoMediaDrm} for use by the manager.
 * @param callback Performs key and provisioning requests.
 * @param optionalKeyRequestParameters An optional map of parameters to pass as the last argument
 *     to {@link MediaDrm#getKeyRequest(byte[], byte[], String, int, HashMap)}. May be null.
 * @see DefaultDrmSessionManager#DefaultDrmSessionManager(java.util.UUID, ExoMediaDrm,
 *     MediaDrmCallback, HashMap)
 */
public OfflineLicenseHelper(
    UUID uuid,
    ExoMediaDrm<T> mediaDrm,
    MediaDrmCallback callback,
    @Nullable HashMap<String, String> optionalKeyRequestParameters) {
  handlerThread = new HandlerThread("OfflineLicenseHelper");
  handlerThread.start();
  conditionVariable = new ConditionVariable();
  DefaultDrmSessionEventListener eventListener =
      new DefaultDrmSessionEventListener() {
        @Override
        public void onDrmKeysLoaded() {
          conditionVariable.open();
        }

        @Override
        public void onDrmSessionManagerError(Exception e) {
          conditionVariable.open();
        }

        @Override
        public void onDrmKeysRestored() {
          conditionVariable.open();
        }

        @Override
        public void onDrmKeysRemoved() {
          conditionVariable.open();
        }
      };
  drmSessionManager =
      new DefaultDrmSessionManager<>(uuid, mediaDrm, callback, optionalKeyRequestParameters);
  drmSessionManager.addListener(new Handler(handlerThread.getLooper()), eventListener);
}
 
Example #22
Source File: Uuid2PosDecimalTable.java    From helper with MIT License 5 votes vote down vote up
/**
 * Adds the specified {@code amount}.
 *
 * @param uuid the uuid
 * @param amount the amount to add
 * @return a promise encapsulating the operation
 */
public Promise<Void> add(UUID uuid, BigDecimal amount) {
    Objects.requireNonNull(uuid, "uuid");
    if (amount.equals(BigDecimal.ZERO)) {
        return Promise.completed(null);
    }
    if (amount.signum() == -1) {
        throw new IllegalArgumentException("amount < 0");
    }

    return doAdd(uuid, amount);
}
 
Example #23
Source File: MicrosoftIISDAVReadFeatureTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testReadMicrosoft() throws Exception {
    final Host host = new Host(new DAVProtocol(), "winbuild.iterate.ch", new Credentials(
        System.getProperties().getProperty("webdav.iis.user"), System.getProperties().getProperty("webdav.iis.password")
    ));
    host.setDefaultPath("/WebDAV");
    final DAVSession session = new DAVSession(host, new DisabledX509TrustManager(), new DefaultX509KeyManager());
    session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    session.getFeature(Touch.class).touch(test, new TransferStatus());
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = new RandomStringGenerator.Builder().build().generate(1000).getBytes();
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);
    IOUtils.write(content, out);
    out.close();
    new DAVUploadFeature(new DAVWriteFeature(session)).upload(
        test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
        new TransferStatus().length(content.length),
        new DisabledConnectionCallback());
    assertTrue(new MicrosoftIISDAVFindFeature(session).find(test));
    assertEquals(content.length, new MicrosoftIISDAVListService(session, new MicrosoftIISDAVAttributesFinderFeature(session)).list(test.getParent(), new DisabledListProgressListener()).get(test).attributes().getSize(), 0L);
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final InputStream in = new MicrosoftIISDAVReadFeature(session).read(test, status, new DisabledConnectionCallback());
    assertNotNull(in);
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
    new StreamCopier(status, status).transfer(in, buffer);
    final byte[] reference = new byte[content.length];
    System.arraycopy(content, 0, reference, 0, content.length);
    assertArrayEquals(reference, buffer.toByteArray());
    in.close();
    new DAVDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #24
Source File: DataStoreQueries.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Store a BaseUser for the player in the database.
 *
 * @param playerUUID UUID of the player.
 * @param registered Time the player registered on the server for the first time.
 * @param playerName Name of the player.
 * @return Executable, use inside a {@link com.djrapitops.plan.storage.database.transactions.Transaction}
 */
public static Executable registerBaseUser(UUID playerUUID, long registered, String playerName) {
    return new ExecStatement(UsersTable.INSERT_STATEMENT) {
        @Override
        public void prepare(PreparedStatement statement) throws SQLException {
            statement.setString(1, playerUUID.toString());
            statement.setString(2, playerName);
            statement.setLong(3, registered);
            statement.setInt(4, 0); // times kicked
        }
    };
}
 
Example #25
Source File: FairyData.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
public FairyData(boolean wasTamperedWith, @NotNull Color primaryColor, @NotNull Color secondaryColor, int age, boolean isDepressed, @Nonnull List<SpellRing> infusedSpell, @Nullable UUID owner, @NotNull IManaCapability handler) {
	this.wasTamperedWith = wasTamperedWith;
	this.primaryColor = primaryColor;
	this.secondaryColor = secondaryColor;
	this.age = age;
	this.isDepressed = isDepressed;
	this.infusedSpell.clear();
	this.infusedSpell.addAll(infusedSpell);
	this.owner = owner;
	this.handler.deserializeNBT(handler.serializeNBT());
}
 
Example #26
Source File: TestStorageContainerManager.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testSCMInitializationFailure()
    throws IOException, AuthenticationException {
  OzoneConfiguration conf = new OzoneConfiguration();
  final String path =
      GenericTestUtils.getTempPath(UUID.randomUUID().toString());
  Path scmPath = Paths.get(path, "scm-meta");
  conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, scmPath.toString());
  exception.expect(SCMException.class);
  exception.expectMessage(
      "SCM not initialized due to storage config failure");
  StorageContainerManager.createSCM(conf);
}
 
Example #27
Source File: SentinelEventHandler.java    From Sentinel with MIT License 5 votes vote down vote up
/**
 * Called when combat occurs in the world (and has not yet been processed by other plugins),
 * to handle things like cancelling invalid damage to/from a Sentinel NPC,
 * changing damage values given to or received from an NPC,
 * and if relevant handling config options that require overriding damage events.
 */
@EventHandler(priority = EventPriority.LOW)
public void whenAttacksAreHappening(EntityDamageByEntityEvent event) {
    if (event.isCancelled()) {
        return;
    }
    UUID victimUuid = event.getEntity().getUniqueId();
    for (SentinelTrait sentinel : cleanCurrentList()) {
        sentinel.whenSomethingMightDie(victimUuid);
    }
    SentinelTrait victim = SentinelUtilities.tryGetSentinel(event.getEntity());
    SentinelTrait attacker = SentinelUtilities.tryGetSentinel(event.getDamager());
    if (victim != null) {
        if (attacker != null && victim.getNPC().getId() == attacker.getNPC().getId()) {
            event.setCancelled(true);
            return;
        }
        victim.whenAttacksAreHappeningToMe(event);
    }
    if (attacker != null) {
        attacker.whenAttacksAreHappeningFromMe(event);
    }
    if (event.getDamager() instanceof Projectile) {
        ProjectileSource source = ((Projectile) event.getDamager()).getShooter();
        if (source instanceof Entity) {
            SentinelTrait shooter = SentinelUtilities.tryGetSentinel((Entity) source);
            if (shooter != null) {
                shooter.whenAttacksAreHappeningFromMyArrow(event);
            }
        }
    }
}
 
Example #28
Source File: NotificationRuleResourceTest.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@Test
public void addProjectToRuleInvalidProjectTest() {
    NotificationPublisher publisher = qm.getNotificationPublisher(DefaultNotificationPublishers.SLACK.getPublisherName());
    NotificationRule rule = qm.createNotificationRule("Example Rule", NotificationScope.PORTFOLIO, NotificationLevel.INFORMATIONAL, publisher);
    Response response = target(V1_NOTIFICATION_RULE + "/" + rule.getUuid().toString() + "/project/" + UUID.randomUUID().toString()).request()
            .header(X_API_KEY, apiKey)
            .post(Entity.json(""));
    Assert.assertEquals(404, response.getStatus(), 0);
    Assert.assertNull(response.getHeaderString(TOTAL_COUNT_HEADER));
    String body = getPlainTextBody(response);
    Assert.assertEquals("The project could not be found.", body);
}
 
Example #29
Source File: GridContinuousProcessor.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param routineId Routine ID.
 */
@SuppressWarnings("TooBroadScope")
private void unregisterRemote(UUID routineId) {
    RemoteRoutineInfo remote;
    LocalRoutineInfo loc;

    stopLock.lock();

    try {
        remote = rmtInfos.remove(routineId);

        loc = locInfos.remove(routineId);

        if (remote == null)
            stopped.add(routineId);
    }
    finally {
        stopLock.unlock();
    }

    if (log.isDebugEnabled())
        log.debug("unregisterRemote [routineId=" + routineId + ", loc=" + loc + ", rmt=" + remote + ']');

    if (remote != null)
        unregisterHandler(routineId, remote.hnd, false);
    else if (loc != null) {
        // Removes routine at node started it when stopRoutine called from another node.
        unregisterHandler(routineId, loc.hnd, false);
    }
}
 
Example #30
Source File: TestOMVolumeCreateResponse.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddToDBBatch() throws Exception {

  String volumeName = UUID.randomUUID().toString();
  String userName = "user1";
  UserVolumeInfo volumeList = UserVolumeInfo.newBuilder()
      .setObjectID(1).setUpdateID(1)
      .addVolumeNames(volumeName).build();

  OMResponse omResponse = OMResponse.newBuilder()
          .setCmdType(OzoneManagerProtocolProtos.Type.CreateVolume)
          .setStatus(OzoneManagerProtocolProtos.Status.OK)
          .setSuccess(true)
          .setCreateVolumeResponse(CreateVolumeResponse.getDefaultInstance())
      .build();

  OmVolumeArgs omVolumeArgs = OmVolumeArgs.newBuilder()
      .setOwnerName(userName).setAdminName(userName)
      .setVolume(volumeName).setCreationTime(Time.now()).build();
  OMVolumeCreateResponse omVolumeCreateResponse =
      new OMVolumeCreateResponse(omResponse, omVolumeArgs, volumeList);

  omVolumeCreateResponse.addToDBBatch(omMetadataManager, batchOperation);

  // Do manual commit and see whether addToBatch is successful or not.
  omMetadataManager.getStore().commitBatchOperation(batchOperation);


  Assert.assertEquals(1,
      omMetadataManager.countRowsInTable(omMetadataManager.getVolumeTable()));
  Assert.assertEquals(omVolumeArgs,
      omMetadataManager.getVolumeTable().iterator().next().getValue());

  Assert.assertEquals(volumeList,
      omMetadataManager.getUserTable().get(
          omMetadataManager.getUserKey(userName)));
}