auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void cleanupRequestIfNoRemainingTasks(SingularityTaskCleanup cleanupTask, Map<String, List<String>> requestIdToTaskIds) { String requestId = cleanupTask.getTaskId().getRequestId(); if (requestIdToTaskIds.get(requestId) == null) { LOG.info("Couldn't find tasks for requestId {}", requestId); return; } List<String> requestTasks = requestIdToTaskIds.get(requestId); requestTasks.remove(cleanupTask.getTaskId().getId()); if (requestTasks.isEmpty()) { LOG.info("All tasks for requestId are now killed", requestId); requestManager.createCleanupRequest( new SingularityRequestCleanup( cleanupTask.getUser(), RequestCleanupType.DELETING, System.currentTimeMillis(), Optional.of(Boolean.TRUE), Optional.absent(), requestId, Optional.<String> absent(), Optional.<Boolean> absent(), cleanupTask.getMessage(), Optional.<String> absent(), Optional.<SingularityShellCommand>absent())); } }

Target:
private void cleanupRequestIfNoRemainingTasks(SingularityTaskCleanup cleanupTask, Map<String, List<String>> requestIdToTaskIds) { String requestId = cleanupTask.getTaskId().getRequestId(); if (requestIdToTaskIds.containsKey(requestId)) { List<String> requestTasks = requestIdToTaskIds.get(requestId); requestTasks.remove(cleanupTask.getTaskId().getId()); if (requestTasks.isEmpty()) { LOG.info("All tasks for requestId are now killed, re-enqueueing request cleanup", requestId); requestManager.createCleanupRequest( new SingularityRequestCleanup( cleanupTask.getUser(), RequestCleanupType.DELETING, System.currentTimeMillis(), Optional.of(Boolean.TRUE), cleanupTask.getRemoveFromLoadBalancer(), requestId, Optional.absent(), Optional.absent(), cleanupTask.getMessage(), Optional.absent(), Optional.absent())); } } }
Source:
public void retryTask(Long activityId) { TaskActivity activity = activityService.getTaskActivityById(activityId); retryNumber += 1; handleTask(taskService.getTask(activity.getTask()), activity.getParameters(), true , retryNumber); }

Target:
public void retryTask(Long activityId) { TaskActivity activity = activityService.getTaskActivityById(activityId); handleTask(taskService.getTask(activity.getTask()), activity.getParameters(), true); }
Source:
private void onSubscribe(ChannelHandlerContext ctx, StompFrame inboundFrame) { String destination = inboundFrame.headers().getAsString(DESTINATION); String subscriptionId = inboundFrame.headers().getAsString(ID); if (destination == null || subscriptionId == null) { sendErrorFrame("missed header", "Required 'destination' or 'id' header missed", ctx); return; } Set<StompSubscription> subscriptions = chatDestinations.putIfAbsent(destination, new HashSet<StompSubscription>()); if (subscriptions == null) { subscriptions = chatDestinations.get(destination); } final StompSubscription subscription = new StompSubscription(subscriptionId, destination, ctx.channel()); if (subscriptions.contains(subscription)) { sendErrorFrame("duplicate subscription", "Received duplicate subscription id=" + subscriptionId, ctx); return; } subscriptions.add(subscription); ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { chatDestinations.get(subscription.destination()).remove(subscription); } }); String receiptId = inboundFrame.headers().getAsString(RECEIPT); if (receiptId != null) { StompFrame receiptFrame = new DefaultStompFrame(StompCommand.RECEIPT); receiptFrame.headers().set(RECEIPT_ID, receiptId); ctx.writeAndFlush(receiptFrame); } }

Target:
private void onSubscribe(ChannelHandlerContext ctx, StompFrame inboundFrame) { String destination = inboundFrame.headers().getAsString(DESTINATION); String subscriptionId = inboundFrame.headers().getAsString(ID); if (destination == null || subscriptionId == null) { sendErrorFrame("missed header", "Required 'destination' or 'id' header missed", ctx); return; } Set<StompSubscription> subscriptions = chatDestinations.get(destination); if (subscriptions == null) { subscriptions = new HashSet<StompSubscription>(); Set<StompSubscription> previousSubscriptions = chatDestinations.putIfAbsent(destination, subscriptions); if (previousSubscriptions != null) { subscriptions = previousSubscriptions; } } final StompSubscription subscription = new StompSubscription(subscriptionId, destination, ctx.channel()); if (subscriptions.contains(subscription)) { sendErrorFrame("duplicate subscription", "Received duplicate subscription id=" + subscriptionId, ctx); return; } subscriptions.add(subscription); ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { chatDestinations.get(subscription.destination()).remove(subscription); } }); String receiptId = inboundFrame.headers().getAsString(RECEIPT); if (receiptId != null) { StompFrame receiptFrame = new DefaultStompFrame(StompCommand.RECEIPT); receiptFrame.headers().set(RECEIPT_ID, receiptId); ctx.writeAndFlush(receiptFrame); } }
Source:
private Optional<Filter> getSpatialFilterOption() { if (spatialFilters == null || spatialFilters.isEmpty()) { return Optional.empty(); } else if (spatialFilters.size() == 1) { return Optional.ofNullable(spatialFilters.get(0)); } else { return Optional.ofNullable(FILTER_FACTORY.or(spatialFilters)); } }

Target:
private Optional<Filter> getSpatialFilterOption() { if (CollectionUtils.isEmpty(spatialFilters)) { return Optional.empty(); } else if (spatialFilters.size() == 1) { return Optional.ofNullable(spatialFilters.get(0)); } else { return Optional.ofNullable(FILTER_FACTORY.or(spatialFilters)); } }
Source:
public TDSavedQuery updateSavedQuery(String name, TDSavedQueryUpdateRequest request) { List<TDSavedQuery> savedQueries = listSavedQueries(); for (TDSavedQuery q : savedQueries) { if (q.getName().equals(name)) { TDSaveQueryRequest fullRequest = request.merge(q); return updateSavedQuery(fullRequest); } } throw new TDClientHttpNotFoundException(String.format("Saved query %s is not found", name)); }

Target:
public TDSavedQuery updateSavedQuery(String name, TDSavedQueryUpdateRequest request) { String json = request.toJson(); TDSavedQuery result = doPost( buildUrl("/v3/schedule/update", name), ImmutableMap.<String, String>of(), Optional.of(json), TDSavedQuery.class); return result; }
Source:
private Node tryFoldKnownMethods(Node subtree) { subtree = tryFoldArrayJoin(subtree); subtree = tryToFoldArrayConcat(subtree); if (subtree.isCall()) { Node callTarget = subtree.getFirstChild(); if (callTarget == null) { return subtree; } if (NodeUtil.isGet(callTarget)) { if (isASTNormalized() && callTarget.getFirstChild().isQualifiedName()) { switch (callTarget.getFirstChild().getQualifiedName()) { case "Math": return tryFoldKnownMathMethods(subtree, callTarget); default: } } subtree = tryFoldKnownStringMethods(subtree, callTarget); } else if (callTarget.isName()) { subtree = tryFoldKnownNumericMethods(subtree, callTarget); } } return subtree; }

Target:
private Node tryFoldKnownMethods(Node subtree) { checkArgument(subtree.isCall(), subtree); subtree = tryFoldArrayJoin(subtree); if (subtree.isCall()) { subtree = tryToFoldArrayConcat(subtree); checkState(subtree.isCall(), subtree); Node callTarget = checkNotNull(subtree.getFirstChild()); if (NodeUtil.isGet(callTarget)) { if (isASTNormalized() && callTarget.getFirstChild().isQualifiedName()) { switch (callTarget.getFirstChild().getQualifiedName()) { case "Math": return tryFoldKnownMathMethods(subtree, callTarget); default: } } subtree = tryFoldKnownStringMethods(subtree, callTarget); } else if (callTarget.isName()) { subtree = tryFoldKnownNumericMethods(subtree, callTarget); } } return subtree; }
Source:
public void testOpenTxnRelication() throws IOException { String name = testName.getMethodName(); String dbName = createDB(name, driver); run("CREATE TABLE " + dbName + ".unptned(a int) PARTITIONED BY (load_date date) CLUSTERED BY(a) INTO 3 BUCKETS STORED AS ORC TBLPROPERTIES ('transactional'='true')", driver); run("CREATE TABLE " + dbName + ".ptned(a string) partitioned by (b int) STORED AS TEXTFILE", driver); run("CREATE TABLE " + dbName + ".unptned_empty(a string) STORED AS TEXTFILE", driver); run("CREATE TABLE " + dbName + ".ptned_empty(a string) partitioned by (b int) STORED AS TEXTFILE", driver); advanceDumpDir(); run("REPL DUMP " + dbName, driver); String replDumpLocn = getResult(0,0,driver); String replDumpId = getResult(0,1,true,driver); LOG.info("Dumped to with id {}",replDumpLocn,replDumpId); run("REPL LOAD " + dbName + "_dupe FROM '" + replDumpLocn + "'", driverMirror); run("INSERT INTO " + dbName + ".unptned values (1)", driver); advanceDumpDir(); run("REPL DUMP " + dbName + " FROM " + replDumpId, driver); String incrementalDumpLocn = getResult(0,0,driver); String incrementalDumpId = getResult(0,1,true,driver); LOG.info("Dumped to with id {}", incrementalDumpLocn, incrementalDumpId); run("REPL LOAD " + dbName + "_dupe FROM '"+incrementalDumpLocn+"'", driverMirror); run("REPL STATUS " + dbName + "_dupe", driverMirror); verifyResults(new String[] {incrementalDumpId}, driverMirror); String[] unptn_data = new String[]{ "1" }; String[] empty = new String[]{}; }

Target:
public void testOpenTxnRelication() throws IOException { String name = testName.getMethodName(); String dbName = createDB(name, driver); advanceDumpDir(); Tuple bootstrap = bootstrapLoadAndVerify(dbName, "default1"); run("CREATE TABLE " + dbName + ".acid(a int) PARTITIONED BY (load_date date) CLUSTERED BY(a) INTO 3 BUCKETS STORED AS ORC TBLPROPERTIES ('transactional'='true')", driver); bootstrap = incrementalLoadAndVerify(dbName,bootstrap.lastReplId,"default1"); run("REPL STATUS " + dbName + "_dupe", driverMirror); verifyResults(new String[] {bootstrap.lastReplId}, driverMirror); }
Source:
public String toString() { return "AMQPMessage [durable=" + isDurable() + ", messageID=" + getMessageID() + ", address=" + getAddress() + ", size=" + getEncodeSize() + ", ApplicationProperties=" + getApplicationProperties() + ", properties=" + getProperties() + ", extraProperties = " + getExtraProperties() + "]"; }

Target:
public String toString() { return "AMQPMessage [durable=" + isDurable() + ", messageID=" + getMessageID() + ", address=" + getAddress() + ", size=" + getEncodeSize() + ", applicationProperties=" + getApplicationProperties() + ", properties=" + getProperties() + ", extraProperties = " + getExtraProperties() + "]"; }
Source:
public PooledLockFactory(boolean fair) { this.fairness = fair; }

Target:
PooledLockFactory(boolean fair) { this.fairness = fair; }
Source:
public String toString() { return String.format( "%s, targetVdsId = %s, action = %s, ip = %s, port = %s, type = %s, user = %s, " + "password = ***, options = '%s', policy = '%s'", super.toString(), getTargetVdsID(), getAction(), getFenceAgent().getIp(), getFenceAgent().getPort(), getFenceAgent().getType(), getFenceAgent().getUser(), getFenceAgent().getOptions(), getFencingPolicy()); }

Target:
public String toString() { return String.format( "%s, targetVdsId = %s, action = %s, agent = '%', policy = '%s'", super.toString(), getTargetVdsID(), getAction(), getFenceAgent(), getFencingPolicy()); }
Source:
public Collection<StatisticType> getAll() { return ImmutableList.copyOf(this.universalStatisticMappings.values()); }

Target:
public Collection<StatisticType> getAll() { return ImmutableList.copyOf(this.statisticTypeMappings.values()); }
Source:
public boolean isArray(final Object o) { if (o instanceof List) { return true; } return false; }

Target:
public boolean isArray(final Object o) { return o instanceof List; }
Source:
protected Control createSWTControl(Composite parent) throws DatabindingFailedException { final Control control = super.createSWTControl(parent); final ComposedAdapterFactory composedAdapterFactory = new ComposedAdapterFactory(new AdapterFactory[] { new ReflectiveItemProviderAdapterFactory(), new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE) }); adapterFactoryItemDelegator = new AdapterFactoryItemDelegator(composedAdapterFactory); return control; }

Target:
protected Control createSWTControl(Composite parent) throws DatabindingFailedException { final Control control = super.createSWTControl(parent); composedAdapterFactory = new ComposedAdapterFactory(new AdapterFactory[] { new ReflectiveItemProviderAdapterFactory(), new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE) }); adapterFactoryItemDelegator = new AdapterFactoryItemDelegator(composedAdapterFactory); return control; }
Source:
public void edit(VmNextRunConfigurationModel object) { driver.edit(object); cpuPanel.setVisible(object.isCpuPluggable()); changedFields.setHTML(SafeHtmlUtils.fromSafeConstant(object.getChangedFields())); }

Target:
public void edit(VmNextRunConfigurationModel object) { driver.edit(object); cpuPanel.setVisible(object.isCpuPluggable()); SafeHtmlBuilder changedFieldsBuilder = new SafeHtmlBuilder(); for (String field: object.getChangedFields()) { String escapedField = SafeHtmlUtils.htmlEscape(field); changedFieldsBuilder.append(listItem(escapedField, templates)); } changedFields.setHTML(changedFieldsBuilder.toSafeHtml()); }
Source:
public IEvaluationResult evaluateExpression(final EObject target, final String expression) { final IInterpreter interpreter = getInterpreter(expression); IEvaluationResult result = null; try { if (interpreter instanceof IInterpreterWithDiagnostic) { result = ((IInterpreterWithDiagnostic) interpreter).evaluateExpression(target, expression); } else { final Object value = interpreter.evaluate(target, expression); result = new IEvaluationResult() { @Override public Object getValue() { return value; } @Override public Diagnostic getDiagnostic() { return Diagnostic.OK_INSTANCE; } }; } } catch (EvaluationException evx) { this.evaluationErrorHandler.get().handleException(evx); result = creatErrorResult(evx); } catch (RuntimeException rex) { this.evaluationErrorHandler.get().handleException(rex); result = creatErrorResult(rex); } return result; }

Target:
public IEvaluationResult evaluateExpression(final EObject target, final String expression) throws EvaluationException { final IInterpreter interpreter = getInterpreter(expression); IEvaluationResult result = null; try { if (interpreter instanceof IInterpreterWithDiagnostic) { result = ((IInterpreterWithDiagnostic) interpreter).evaluateExpression(target, expression); } else { final Object value = interpreter.evaluate(target, expression); result = new IEvaluationResult() { @Override public Object getValue() { return value; } @Override public Diagnostic getDiagnostic() { return Diagnostic.OK_INSTANCE; } }; } } catch (EvaluationException evx) { this.evaluationErrorHandler.get().handleException(evx); result = creatErrorResult(evx); } catch (RuntimeException rex) { this.evaluationErrorHandler.get().handleException(rex); result = creatErrorResult(rex); } return result; }
Source:
static void validateHeapHeadroom(NodeMemoryConfig config, long availableMemory) { long maxQueryTotalMemoryPerNode = config.getMaxQueryTotalMemoryPerNode().toBytes(); long heapHeadroom = config.getHeapHeadroom().toBytes(); if (heapHeadroom < 0 || heapHeadroom + maxQueryTotalMemoryPerNode > availableMemory) { throw new IllegalArgumentException( format("Invalid memory configuration. The sum of max query memory per node (%s) and heap headroom (%s) cannot be larger than the available heap memory (%s)", maxQueryTotalMemoryPerNode, heapHeadroom, availableMemory)); } }

Target:
static void validateHeapHeadroom(NodeMemoryConfig config, long availableMemory) { long maxQueryTotalMemoryPerNode = config.getMaxQueryTotalMemoryPerNode().toBytes(); long heapHeadroom = config.getHeapHeadroom().toBytes(); if (heapHeadroom < 0 || heapHeadroom + maxQueryTotalMemoryPerNode > availableMemory) { throw new IllegalArgumentException( format("Invalid memory configuration. The sum of max total query memory per node (%s) and heap headroom (%s) cannot be larger than the available heap memory (%s)", maxQueryTotalMemoryPerNode, heapHeadroom, availableMemory)); } }
Source:
private static Map<Integer,Long> fetchClusterCountsFromModel(JavaRDD<Vector> trainPointData, final KMeansModel model) { return trainPointData.map(new Function<Vector, Integer>() { @Override public Integer call(Vector vector) throws Exception { return model.predict(vector); } }).countByValue(); }

Target:
private static Map<Integer,Long> fetchClusterCountsFromModel(JavaRDD<Vector> trainPointData, final KMeansModel model) { return trainPointData.map(new Function<Vector, Integer>() { @Override public Integer call(Vector vector) { return model.predict(vector); } }).countByValue(); }
Source:
public Object handle(CommandMessage<?> command) throws Exception { VersionedAggregateIdentifier iv = commandTargetResolver.resolveTarget(command); Aggregate<T> inst = repository.loadOrCreate(iv.getIdentifier(), iv.getVersion(), factoryMethod); Object result = inst.handle(command); assertThat(inst.identifier(), id -> id != null && id.equals(iv.getIdentifier()), "Identifier must be set after handling the message"); return result; }

Target:
public Object handle(CommandMessage<?> command) throws Exception { VersionedAggregateIdentifier iv = commandTargetResolver.resolveTarget(command); Aggregate<T> inst = repository.loadOrCreate(iv.getIdentifier(), factoryMethod); Object result = inst.handle(command); assertThat(inst.identifier(), id -> id != null && id.equals(iv.getIdentifier()), "Identifier must be set after handling the message"); return result; }
Source:
public ListenableFuture<?> reserve(QueryId queryId, String allocationTag, long bytes) { checkArgument(bytes >= 0, "bytes is negative"); ListenableFuture<?> result; if (bytes != 0) { boolean done = false; while (!done) { if (queryMemoryReservations.computeIfPresent(queryId, (k, v) -> v + bytes) != null) { done = true; updateTaggedMemoryAllocations(queryId, allocationTag, bytes, false); } else { synchronized (this) { if (queryMemoryReservations.putIfAbsent(queryId, bytes) == null) { done = true; updateTaggedMemoryAllocations(queryId, allocationTag, bytes, true); } } } } } synchronized (this) { reservedBytes += bytes; if (getFreeBytes() <= 0) { if (future == null) { future = NonCancellableMemoryFuture.create(); } checkState(!future.isDone(), "future is already completed"); result = future; } else { result = NOT_BLOCKED; } } onMemoryReserved(); return result; }

Target:
public ListenableFuture<?> reserve(QueryId queryId, String allocationTag, long bytes) { checkArgument(bytes >= 0, "bytes is negative"); ListenableFuture<?> result; if (bytes != 0) { while (true) { if (queryMemoryReservations.computeIfPresent(queryId, (ignored, value) -> value + bytes) != null) { updateTaggedMemoryAllocations(queryId, allocationTag, bytes, false); break; } synchronized (this) { if (queryMemoryReservations.putIfAbsent(queryId, bytes) == null) { updateTaggedMemoryAllocations(queryId, allocationTag, bytes, true); break; } } } } synchronized (this) { reservedBytes += bytes; if (getFreeBytes() <= 0) { if (future == null) { future = NonCancellableMemoryFuture.create(); } checkState(!future.isDone(), "future is already completed"); result = future; } else { result = NOT_BLOCKED; } } onMemoryReserved(); return result; }
Source:
public void changeHashedPassword(User user, String hashedPassword, String salt) throws APIException { OpenmrsUtil.validatePassword(user.getUsername(), hashedPassword, user.getSystemId()); dao.changeHashedPassword(user, hashedPassword, salt); }

Target:
public void changeHashedPassword(User user, String hashedPassword, String salt) throws APIException { dao.changeHashedPassword(user, hashedPassword, salt); }
Source:
private ByteBuffer readNextChunk() throws IOException { int chunkSize = readChunkSize(); byte[] buffer = new byte[chunkSize]; int read = in.read( buffer ); if(read == -1) { throwConnectionLost(); } else if(read != chunkSize) { throw new UnsupportedOperationException( "Unable to read chunk, chunk split across packet boundaries not " + "yet supported." ); } ByteBuffer chunk = ByteBuffer.allocate( chunkSize ); chunk.put( buffer ); chunk.flip(); return chunk; }

Target:
private ByteBuffer readNextChunk() throws IOException { int chunkSize = readChunkSize(); byte[] buffer = new byte[chunkSize]; InputStreams.readAll( in, buffer ); return ByteBuffer.wrap( buffer ); }
Source:
public void testApplication() throws IOException, Exception { try { File file = new File(FILE_PATH); file.delete(); getConfig(); qNameToUse = conf.get("dt.operator.amqIn.prop.subject"); createAMQClient(); writeToQueue(); closeClient(); LocalMode.Controller lc = asyncRun(); chkOutput(); compare(); lc.shutdown(); broker.stop(); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }

Target:
public void testApplication() throws IOException, Exception { try { File file = new File(FILE_PATH); file.delete(); getConfig(); createAMQClient(brokerURL); writeToQueue(); closeClient(); LocalMode.Controller lc = asyncRun(); chkOutput(); compare(); lc.shutdown(); broker.stop(); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }
Source:
public void noCrashOnCommittedRequestsOfUnSeenRequestTest() throws Exception { final String path = "/noCrash/OnCommittedRequests/OfUnSeenRequestTest"; final int iteration = 10; final int sessionid = 0x123456; final int firstCXid = 0x100; int readReqId = firstCXid; processor.stoppedMainLoop = true; HashSet<Request> localRequests = new HashSet<Request>(); Request firstCommittedReq = newRequest( new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()), OpCode.create, sessionid, readReqId++); processor.queuedRequests.add(firstCommittedReq); localRequests.add(firstCommittedReq); for (; readReqId <= iteration+firstCXid; ++readReqId) { Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, sessionid, readReqId); processor.queuedRequests.add(readReq); localRequests.add(readReq); } Assert.assertTrue(processor.queuedRequests.containsAll(localRequests)); processor.initThreads(iteration* 2); processor.run(); Assert.assertTrue(processedRequests.isEmpty()); Request preSessionCommittedReq = newRequest( new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()), OpCode.create, sessionid, firstCXid - 2); processor.committedRequests.add(preSessionCommittedReq); processor.committedRequests.add(firstCommittedReq); processor.run(); Assert.assertTrue(processedRequests.peek() == preSessionCommittedReq); processor.run(); Assert.assertTrue(processedRequests.containsAll(localRequests)); }

Target:
public void noCrashOnCommittedRequestsOfUnSeenRequestTest() throws Exception { final String path = "/noCrash/OnCommittedRequests/OfUnSeenRequestTest"; final int numberofReads = 10; final int sessionid = 0x123456; final int firstCXid = 0x100; int readReqId = firstCXid; processor.stoppedMainLoop = true; HashSet<Request> localRequests = new HashSet<Request>(); Request firstCommittedReq = newRequest( new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()), OpCode.create, sessionid, readReqId++); processor.queuedRequests.add(firstCommittedReq); localRequests.add(firstCommittedReq); for (; readReqId <= numberofReads+firstCXid; ++readReqId) { Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, sessionid, readReqId); processor.queuedRequests.add(readReq); localRequests.add(readReq); } Assert.assertTrue(processor.queuedRequests.containsAll(localRequests)); processor.initThreads(numberofReads* 2); processor.run(); Assert.assertTrue(processedRequests.isEmpty()); Request preSessionCommittedReq = newRequest( new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()), OpCode.create, sessionid, firstCXid - 2); processor.committedRequests.add(preSessionCommittedReq); processor.committedRequests.add(firstCommittedReq); processor.run(); Assert.assertTrue(processedRequests.peek() == preSessionCommittedReq); processor.run(); Assert.assertTrue(processedRequests.containsAll(localRequests)); }
Source:
private boolean updateCommandWaitingForEvent(CommandEntity cmdEntity) { if (cmdEntity.isWaitingForEVent()) { CallbackTiming callbackTiming = commandsRepository.getCallbackTiming(cmdEntity.getRootCommandId()); if (callbackTiming.getWaitOnEventEndTime() > System.currentTimeMillis()) { cmdEntity.setWaitingForEVent(false); return false; } return true; } return false; }

Target:
private boolean updateCommandWaitingForEvent(CommandEntity cmdEntity) { if (cmdEntity.isWaitingForEVent()) { CallbackTiming callbackTiming = commandsRepository.getCallbackTiming(cmdEntity.getRootCommandId()); if (callbackTiming.getWaitOnEventEndTime() > System.currentTimeMillis()) { commandsRepository.removeEventSubscription(cmdEntity.getId()); cmdEntity.setWaitingForEVent(false); return false; } return true; } return false; }
Source:
public void setDecimal128(long columnKey, Decimal128 value) { }

Target:
public void setDecimal128(long columnKey, Decimal128 value) { throw new IllegalStateException(QUERY_NOT_RETURNED_MESSAGE); }
Source:
public void testReportTitle() throws IOException { Path htmlPath = Paths.get(System.getProperty("user.dir"), "target", "site", "project-reports.html"); assertThat(Files.exists(htmlPath), is(true)); Document document = Jsoup.parse(htmlPath.toFile(), Charset.forName("UTF-8").toString()); Elements leftNav = document.select("#leftColumn [href=\"japicmp.html\"]"); assertThat(leftNav.attr("title"), is("japicmp")); assertThat(leftNav.text(), is("japicmp")); Elements overviewRow = document.select("#bodyColumn tr:has([href=\"japicmp.html\"])"); Elements link = overviewRow.select("[href=\"japicmp.html\"]"); assertThat(link.text(), is("japicmp")); Elements description = overviewRow.select("td:eq(1)"); assertThat(description.text(), is("Source compatibility of japicmp-test-v2-0.8.2-SNAPSHOT.jar against japicmp-test-v2-0.8.2-SNAPSHOT.jar")); }

Target:
public void testReportTitle() throws IOException { Path htmlPath = Paths.get(System.getProperty("user.dir"), "target", "site", "project-reports.html"); assertThat(Files.exists(htmlPath), is(true)); Document document = Jsoup.parse(htmlPath.toFile(), "UTF-8"); Elements leftNav = document.select("#leftColumn [href=\"japicmp.html\"]"); assertThat(leftNav.attr("title"), is("japicmp")); assertThat(leftNav.text(), is("japicmp")); Elements overviewRow = document.select("#bodyColumn tr:has([href=\"japicmp.html\"])"); Elements link = overviewRow.select("[href=\"japicmp.html\"]"); assertThat(link.text(), is("japicmp")); Elements description = overviewRow.select("td:eq(1)"); String projectVersion = System.getProperty("project.version"); assertThat(description.text(), is("Source compatibility of japicmp-test-v2-"+projectVersion + ".jar against japicmp-test-v1-"+ projectVersion + ".jar")); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getMissingServerHooks().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_NO_CONFLICT_SERVERS); return false; } for (GlusterServerHook serverHook: getMissingServerHooks()) { VDS vds = getVdsDAO().get(serverHook.getServerId()); if (vds == null || vds.getStatus() != VDSStatus.Up) { String vdsName = vds != null ? vds.getName() : "NO SERVER"; setVdsName(vdsName); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_SERVER_STATUS_NOT_UP); addCanDoActionMessage(String.format("$%1$s %2$s", "VdsName", vdsName)); return false; } } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getMissingServerHooks().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_NO_CONFLICT_SERVERS); return false; } for (GlusterServerHook serverHook: getMissingServerHooks()) { VDS vds = getVdsDAO().get(serverHook.getServerId()); if (vds == null || vds.getStatus() != VDSStatus.Up) { String vdsName = vds != null ? vds.getName() : GlusterConstants.NO_SERVER; setVdsName(vdsName); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_SERVER_STATUS_NOT_UP); addCanDoActionMessage(String.format("$%1$s %2$s", "VdsName", vdsName)); return false; } } return true; }
Source:
Map<String, MessageAttributeValue> translateAttributes(Map<String, Object> headers, Exchange exchange) { Map<String, MessageAttributeValue> result = new HashMap<>(); HeaderFilterStrategy headerFilterStrategy = getEndpoint().getHeaderFilterStrategy(); for (Entry<String, Object> entry : headers.entrySet()) { if (!headerFilterStrategy.applyFilterToCamelHeaders(entry.getKey(), entry.getValue(), exchange)) { Object value = entry.getValue(); if (value instanceof String && !((String)value).isEmpty()) { MessageAttributeValue mav = new MessageAttributeValue(); mav.setDataType("String"); mav.withStringValue((String)value); result.put(entry.getKey(), mav); } else if (value instanceof ByteBuffer) { MessageAttributeValue mav = new MessageAttributeValue(); mav.setDataType("Binary"); mav.withBinaryValue((ByteBuffer)value); result.put(entry.getKey(), mav); } else if (value instanceof Date) { MessageAttributeValue mav = new MessageAttributeValue(); mav.setDataType("String"); mav.withStringValue(value.toString()); result.put(entry.getKey(), mav); } else if (value instanceof List && ((List) value).size()>0) { String delimiter = "\", \"", prefix = "[\"", suffix = "\"]"; MessageAttributeValue mav = new MessageAttributeValue(); mav.setDataType("String.Array"); mav.withStringValue((String) ((List)value).stream().map(Object::toString).collect(Collectors.joining(delimiter, prefix, suffix))); result.put(entry.getKey(), mav); } else { log.warn("Cannot put the message header key={}, value={} into Sns MessageAttribute", entry.getKey(), entry.getValue()); } } } return result; }

Target:
Map<String, MessageAttributeValue> translateAttributes(Map<String, Object> headers, Exchange exchange) { Map<String, MessageAttributeValue> result = new HashMap<>(); HeaderFilterStrategy headerFilterStrategy = getEndpoint().getHeaderFilterStrategy(); for (Entry<String, Object> entry : headers.entrySet()) { if (!headerFilterStrategy.applyFilterToCamelHeaders(entry.getKey(), entry.getValue(), exchange)) { Object value = entry.getValue(); if (value instanceof String && !((String)value).isEmpty()) { MessageAttributeValue mav = new MessageAttributeValue(); mav.setDataType("String"); mav.withStringValue((String)value); result.put(entry.getKey(), mav); } else if (value instanceof ByteBuffer) { MessageAttributeValue mav = new MessageAttributeValue(); mav.setDataType("Binary"); mav.withBinaryValue((ByteBuffer)value); result.put(entry.getKey(), mav); } else if (value instanceof Date) { MessageAttributeValue mav = new MessageAttributeValue(); mav.setDataType("String"); mav.withStringValue(value.toString()); result.put(entry.getKey(), mav); } else if (value instanceof List) { String resultString = ((List<?>) value).stream() .map(o -> o instanceof String ? String.format("\"%s\"", o) : Objects.toString(o)) .collect(Collectors.joining(", ")); MessageAttributeValue mav = new MessageAttributeValue(); mav.setDataType("String.Array"); mav.withStringValue("[" + resultString + "]"); result.put(entry.getKey(), mav); } else { log.warn("Cannot put the message header key={}, value={} into Sns MessageAttribute", entry.getKey(), entry.getValue()); } } } return result; }
Source:
private void createMongoIndex(final DBCollection dbColl, final DBObject keys, final DBObject options) { try { dbColl.createIndex(keys, options); } catch (MongoCommandException ex) { if (options.containsField("dropOutdated") && getBoolean(options, "dropOutdated", false)) { final BsonDocument errorDocument = ex.getResponse(); if (errorDocument.getInt32("code").intValue() == 85) { String indexName; if (options.containsKey("name")) { indexName = getString(options, "name"); } else { final BsonString errorMessage = errorDocument.getString("errmsg"); final String[] errorSplit = errorMessage.getValue().split("\\s"); indexName = errorSplit[3]; } dbColl.dropIndex(indexName); dbColl.createIndex(keys, options); return; } } throw ex; } }

Target:
private void createMongoIndex(final DBCollection dbColl, final DBObject keys, final DBObject options) { try { dbColl.createIndex(keys, options); } catch (MongoCommandException ex) { final BasicDBObject basicOptions = (BasicDBObject) options; if (basicOptions.getBoolean("dropOutdated", false)) { final BsonDocument errorDocument = ex.getResponse(); if (errorDocument.getInt32("code").intValue() == 85) { String indexName; if (options.containsKey("name")) { indexName = basicOptions.getString("name"); } else { final BsonString errorMessage = errorDocument.getString("errmsg"); final String[] errorSplit = errorMessage.getValue().split("\\s"); indexName = errorSplit[3]; } dbColl.dropIndex(indexName); dbColl.createIndex(keys, options); return; } } throw ex; } }
Source:
protected boolean canDoAction() { if (getVm() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); return false; } if (!canRunActionOnNonManagedVm()) { return false; } if (!isSpecifiedDisksExist(getParameters().getDisks())) { return false; } VmValidator vmValidator = createVmValidator(); SnapshotsValidator snapshotValidator = createSnapshotValidator(); StoragePoolValidator spValidator = createStoragePoolValidator(); if (!(validateVM(vmValidator) && validate(spValidator.isUp()) && validate(vmValidator.vmNotIlegal()) && validate(vmValidator.vmNotLocked()) && validate(snapshotValidator.vmNotDuringSnapshot(getVmId())) && validate(snapshotValidator.vmNotInPreview(getVmId())) && validate(vmValidator.vmNotDuringMigration()) && validate(vmValidator.vmNotRunningStateless()))) { return false; } List<DiskImage> disksList = getDisksListForChecks(); MultipleStorageDomainsValidator sdValidator = createMultipleStorageDomainsValidator(disksList); if (disksList.size() > 0) { DiskImagesValidator diskImagesValidator = createDiskImageValidator(disksList); if (!(validate(diskImagesValidator.diskImagesNotLocked()) && validate(diskImagesValidator.diskImagesNotIllegal()) && validate(sdValidator.allDomainsExistAndActive()))) { return false; } } List<DiskImage> cloneDisksList = getMemoryImageBuilder().getDisksToBeCreated(); if (!validateSpaceRequirements(sdValidator, disksList, cloneDisksList)) { return false; } if (getParameters().isSaveMemory() && Guid.Empty.equals(getStorageDomainIdForVmMemory())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND); } return true; }

Target:
protected boolean canDoAction() { if (getVm() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); return false; } if (!canRunActionOnNonManagedVm()) { return false; } if (!isSpecifiedDisksExist(getParameters().getDisks())) { return false; } VmValidator vmValidator = createVmValidator(); SnapshotsValidator snapshotValidator = createSnapshotValidator(); StoragePoolValidator spValidator = createStoragePoolValidator(); if (!(validateVM(vmValidator) && validate(spValidator.isUp()) && validate(vmValidator.vmNotIlegal()) && validate(vmValidator.vmNotLocked()) && validate(snapshotValidator.vmNotDuringSnapshot(getVmId())) && validate(snapshotValidator.vmNotInPreview(getVmId())) && validate(vmValidator.vmNotDuringMigration()) && validate(vmValidator.vmNotRunningStateless()))) { return false; } List<DiskImage> disksList = getDisksListForChecks(); if (disksList.size() > 0) { DiskImagesValidator diskImagesValidator = createDiskImageValidator(disksList); if (!(validate(diskImagesValidator.diskImagesNotLocked()) && validate(diskImagesValidator.diskImagesNotIllegal()))) { return false; } } if (!validateStorageDomains(disksList)) { return false; } if (getParameters().isSaveMemory() && Guid.Empty.equals(getStorageDomainIdForVmMemory())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND); } return true; }
Source:
private void errorOccurred(RecordFlow triggeringFlow, Throwable t) { synchronized (lockObject) { if (!hasValidSubscriber()) { log.warn( "{}: [SubscriptionLifetime] - (FanOutRecordsPublisher#errorOccurred) @ id: -- Subscriber is null", shardId, flow.connectionStartedAt, flow.subscribeToShardId); return; } String category = throwableCategory(t); if (isActiveFlow(triggeringFlow)) { if (flow != null) { log.warn("{}: [SubscriptionLifetime] - (FanOutRecordsPublisher#errorOccurred) @ id: -- {}", shardId, flow.connectionStartedAt, flow.subscribeToShardId, category, t); flow.cancel(); } log.debug("{}: outstandingRequests zeroing from {}", shardId, outstandingRequests); outstandingRequests = 0; try { if (t.getCause() instanceof ResourceNotFoundException) { log.warn( "{}: Could not call SubscribeToShard successfully because shard no longer exists. Marking shard for completion.", shardId); subscriber.onNext(ProcessRecordsInput.builder().records(Collections.emptyList()) .isAtShardEnd(true).build()); subscriber.onComplete(); } else { subscriber.onError(t); } } catch (Throwable innerThrowable) { log.warn("{}: Exception while calling subscriber.onError", shardId, innerThrowable); } subscriber = null; flow = null; } else { if (triggeringFlow != null) { log.debug( "{}: [SubscriptionLifetime] - (FanOutRecordsPublisher#errorOccurred) @ id: -- -> triggeringFlow wasn't the active flow. Didn't dispatch error", shardId, triggeringFlow.connectionStartedAt, triggeringFlow.subscribeToShardId, category); triggeringFlow.cancel(); } } } }

Target:
private void errorOccurred(RecordFlow triggeringFlow, Throwable t) { synchronized (lockObject) { if (!hasValidSubscriber()) { log.warn( "{}: [SubscriptionLifetime] - (FanOutRecordsPublisher#errorOccurred) @ id: -- Subscriber is null", shardId, flow.connectionStartedAt, flow.subscribeToShardId); return; } String category = throwableCategory(t); if (isActiveFlow(triggeringFlow)) { if (flow != null) { log.warn("{}: [SubscriptionLifetime] - (FanOutRecordsPublisher#errorOccurred) @ id: -- {}", shardId, flow.connectionStartedAt, flow.subscribeToShardId, category, t); flow.cancel(); } log.debug("{}: outstandingRequests zeroing from {}", shardId, outstandingRequests); outstandingRequests = 0; try { handleFlowError(t); } catch (Throwable innerThrowable) { log.warn("{}: Exception while calling subscriber.onError", shardId, innerThrowable); } subscriber = null; flow = null; } else { if (triggeringFlow != null) { log.debug( "{}: [SubscriptionLifetime] - (FanOutRecordsPublisher#errorOccurred) @ id: -- -> triggeringFlow wasn't the active flow. Didn't dispatch error", shardId, triggeringFlow.connectionStartedAt, triggeringFlow.subscribeToShardId, category); triggeringFlow.cancel(); } } } }
Source:
public void onNext(SubscriptionUpdate value) { SubscriptionUpdate.UpdateCase updateCase = value.getUpdateCase(); switch (updateCase) { case ENTITY_UPDATES: value.getEntityUpdates() .getUpdateList() .stream() .map(EntityStateUpdate::getState) .map(any -> (M) unpack(any)) .forEach(delegate::onNext); break; case EVENT_UPDATES: value.getEventUpdates() .getEventList() .stream() .map(e -> (M) e) .forEach(delegate::onNext); break; case UPDATE_NOT_SET: default: throw unsupported("Unsupported update case `%s`.", updateCase); } }

Target:
public void onNext(SubscriptionUpdate value) { UpdateCase updateCase = value.getUpdateCase(); switch (updateCase) { case ENTITY_UPDATES: value.getEntityUpdates() .getUpdateList() .stream() .filter(u -> u.getKindCase() == EntityStateUpdate.KindCase.STATE) .map(EntityStateUpdate::getState) .map(any -> (M) unpack(any)) .forEach(delegate::onNext); break; case EVENT_UPDATES: value.getEventUpdates() .getEventList() .stream() .map(e -> (M) e) .forEach(delegate::onNext); break; case UPDATE_NOT_SET: default: throw unsupported("Unsupported update case `%s`.", updateCase); } }
Source:
public KafkaEmitter(KafkaEmitterConfig config, ObjectMapper jsonMapper) { this.config = config; this.jsonMapper = jsonMapper; this.producer = getKafkaProducer(config); this.producerCallback = new Callback() { @Override public void onCompletion(RecordMetadata recordMetadata, Exception e) { if(e != null) { log.warn(e, "Exception is occured! Retry."); } } }; }

Target:
public KafkaEmitter(KafkaEmitterConfig config, ObjectMapper jsonMapper) { this.config = config; this.jsonMapper = jsonMapper; this.producer = setKafkaProducer(); this.producerCallback = setProducerCallback(); long queueMemoryBound = Long.parseLong(this.config.getKafkaProducerConfig() .getOrDefault(ProducerConfig.BUFFER_MEMORY_CONFIG, "33554432")); this.metricQueue = new MemoryBoundLinkedBlockingQueue<>(queueMemoryBound); this.alertQueue = new MemoryBoundLinkedBlockingQueue<>(queueMemoryBound); this.scheduler = Executors.newScheduledThreadPool(3); this.metricLost = new AtomicLong(0L); this.alertLost = new AtomicLong(0L); this.invalidLost = new AtomicLong(0L); }
Source:
public TopologySummary getTopologySummaryByName(String name) throws AuthorizationException, TException { return getNimbus().getTopologySummaryByName(name); }

Target:
public TopologySummary getTopologySummaryByName(String name) throws TException { return getNimbus().getTopologySummaryByName(name); }
Source:
public void batchUpdate(final String ryaInstanceName, final String pcjId) throws InstanceDoesNotExistException, PCJDoesNotExistException, RyaClientException { requireNonNull(ryaInstanceName); requireNonNull(pcjId); Preconditions.checkState(instanceExists.exists(ryaInstanceName), "The instance: " + ryaInstanceName + " does not exist."); verifyPCJState(ryaInstanceName, pcjId, mongoClient); updatePCJResults(ryaInstanceName, pcjId, mongoClient); updatePCJMetadata(ryaInstanceName, pcjId, mongoClient); }

Target:
public void batchUpdate(final String ryaInstanceName, final String pcjId) throws InstanceDoesNotExistException, PCJDoesNotExistException, RyaClientException { requireNonNull(ryaInstanceName); requireNonNull(pcjId); checkState(instanceExists.exists(ryaInstanceName), "The instance: " + ryaInstanceName + " does not exist."); verifyPCJState(ryaInstanceName, pcjId, mongoClient); updatePCJResults(ryaInstanceName, pcjId, mongoClient); updatePCJMetadata(ryaInstanceName, pcjId, mongoClient); }
Source:
private Score score(Item subject, Item candidate) { return subject.getYear().equals(candidate.getYear()) ? matchScore : Score.nullScore(); }

Target:
private Score score(Item subject, Item candidate) { if (subject.getYear() == null || candidate.getYear() == null) { return Score.nullScore(); } return subject.getYear().equals(candidate.getYear()) ? matchScore : Score.ZERO; }
Source:
public ConsolePasswordFinder(Console console, String promptFormat, int maxTries) { this.console = console; this.promptFormat = promptFormat; this.maxTries = maxTries; this.numTries = 0; }

Target:
public ConsolePasswordFinder(Console console, String promptFormat, int maxTries) { checkFormatString(promptFormat); this.console = console; this.promptFormat = promptFormat; this.maxTries = maxTries; this.numTries = 0; }
Source:
private void addChildren(ITmfStateSystem ss, Builder<@NonNull TimeGraphEntryModel> builder, int quark, long parentId) { for (Integer child : ss.getSubAttributes(quark, false)) { long childId = getId(child); builder.add(new TimeGraphEntryModel(childId, parentId, ss.getAttributeName(child), ss.getStartTime(), Long.MAX_VALUE)); addChildren(ss, builder, child, childId); } }

Target:
private void addChildren(ITmfStateSystem ss, Builder<@NonNull TimeGraphEntryModel> builder, int quark, long parentId) { for (Integer child : ss.getSubAttributes(quark, false)) { long childId = getId(child); builder.add(new TimeGraphEntryModel(childId, parentId, ss.getAttributeName(child), ss.getStartTime(), ss.getCurrentEndTime())); addChildren(ss, builder, child, childId); } }
Source:
protected int localInstancesCount(IgniteUuid srvcId) { Collection<ServiceContextImpl> ctxs = locServices.get(srvcId); return ctxs != null ? ctxs.size() : 0; }

Target:
int localInstancesCount(IgniteUuid srvcId) { Collection<ServiceContextImpl> ctxs = locServices.get(srvcId); if (ctxs == null) return 0; synchronized (ctxs) { return ctxs.size(); } }
Source:
protected Collection<String> getSuggestedNames(final HaxeExpression expression) { Collection<String> candidates = new LinkedHashSet<String>(); String text = expression.getText(); if (expression instanceof HaxeCallExpression) { final HaxeExpression callee = ((HaxeCallExpression)expression).getExpression(); text = callee.getText(); } else if (expression instanceof HaxeRegularExpression) { text = "REGEX"; } else if (expression instanceof HaxeLiteralExpression) { text = "CONST_" + expression.getText().toUpperCase(); } if (text != null) { candidates.addAll(HaxeNameSuggesterUtil.generateNames(text)); } if (candidates.isEmpty()) { candidates.add("x"); } final Set<String> usedNames = HaxeRefactoringUtil.collectUsedNames(expression); usedNames.addAll(HaxeRefactoringUtil.collectKeywords()); final Collection<String> result = new ArrayList<String>(); for (String candidate : candidates) { int index = 0; String suffix = ""; while (usedNames.contains(candidate + suffix)) { suffix = Integer.toString(++index); } result.add(candidate + suffix); } return result; }

Target:
protected Collection<String> getSuggestedNames(final HaxeExpression expression) { return HaxeNameSuggesterUtil.getSuggestedNames(expression, false); }
Source:
public void deleteSecurityTeam(PerunSession sess, SecurityTeam securityTeam, boolean forceDelete) throws SecurityTeamNotExistsException, InternalErrorException, RelationExistsException { List<User> blacklist = getSecurityTeamsManagerImpl().getBlacklist(sess, Collections.singletonList(securityTeam)); if (blacklist != null && !blacklist.isEmpty() && !forceDelete) { throw new RelationExistsException("SecurityTeam has blacklisted users."); } if (blacklist != null) { for (User blacklistedUser : blacklist) { getPerunBl().getSecurityTeamsManagerBl().removeUserFromBlacklist(sess, securityTeam, blacklistedUser); } } List<Facility> facilities = getPerunBl().getFacilitiesManagerBl().getAssignedFacilities(sess, securityTeam); if (facilities != null && !facilities.isEmpty() && !forceDelete) { throw new RelationExistsException("SecurityTeam is assigned to some facilities."); } if (facilities != null) { for (Facility facility : facilities) { getPerunBl().getFacilitiesManagerBl().removeSecurityTeam(sess, facility, securityTeam); } } getSecurityTeamsManagerImpl().deleteSecurityTeam(sess, securityTeam); getPerunBl().getAuditer().log(sess,new SecurityTeamDeleted(securityTeam)); }

Target:
public void deleteSecurityTeam(PerunSession sess, SecurityTeam securityTeam, boolean forceDelete) throws SecurityTeamNotExistsException, InternalErrorException, RelationExistsException { List<User> blacklist = getSecurityTeamsManagerImpl().getBlacklist(sess, Collections.singletonList(securityTeam)); if (!blacklist.isEmpty() && !forceDelete) { throw new RelationExistsException("SecurityTeam has blacklisted users."); } for (User blacklistedUser : blacklist) { getPerunBl().getSecurityTeamsManagerBl().removeUserFromBlacklist(sess, securityTeam, blacklistedUser); } List<Facility> facilities = getPerunBl().getFacilitiesManagerBl().getAssignedFacilities(sess, securityTeam); if (!facilities.isEmpty() && !forceDelete) { throw new RelationExistsException("SecurityTeam is assigned to some facilities."); } for (Facility facility : facilities) { getPerunBl().getFacilitiesManagerBl().removeSecurityTeam(sess, facility, securityTeam); } getSecurityTeamsManagerImpl().deleteSecurityTeam(sess, securityTeam); getPerunBl().getAuditer().log(sess,new SecurityTeamDeleted(securityTeam)); }