auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean isEnabled() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IWorkbenchPart part = page.getActivePart(); if (part == null) { return false; } ISelectionProvider selectionProvider = part.getSite().getSelectionProvider(); if (selectionProvider == null) { return false; } ISelection selection = selectionProvider.getSelection(); Object firstElement = ((IStructuredSelection) selection).getFirstElement(); final TmfCommonProjectElement traceElem = (firstElement instanceof TmfTraceElement) ? ((TmfTraceElement) firstElement).getElementUnderTraceFolder() : (TmfCommonProjectElement) firstElement; if (!traceElem.getTraceType().equals(TRACE_TYPE_ID)) { return false; } int arraySize = 0; try <START> (FileReader fileReader = new FileReader(traceElem.getLocation().getPath())) { <END> try (JsonReader reader = new JsonReader(fileReader);) { Gson gson = new Gson(); JsonObject object = gson.fromJson(reader, JsonObject.class); arraySize = object.get(DATA_KEY).getAsJsonArray().size(); } } catch (IOException e) { return false; } return arraySize > 1; }</code><technical_language>do FileReader fileReader = new FileReader(traceElem.getLocation().getPath()); JsonReader reader = new JsonReader(fileReader)</technical_language>

Target:
public boolean isEnabled() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IWorkbenchPart part = page.getActivePart(); if (part == null) { return false; } ISelectionProvider selectionProvider = part.getSite().getSelectionProvider(); if (selectionProvider == null) { return false; } ISelection selection = selectionProvider.getSelection(); Object firstElement = ((IStructuredSelection) selection).getFirstElement(); final TmfCommonProjectElement traceElem = (firstElement instanceof TmfTraceElement) ? ((TmfTraceElement) firstElement).getElementUnderTraceFolder() : (TmfCommonProjectElement) firstElement; if (!traceElem.getTraceType().equals(TRACE_TYPE_ID)) { return false; } int arraySize = 0; try (FileReader fileReader = new FileReader(traceElem.getLocation().getPath())) { try (JsonReader reader = new JsonReader(fileReader)) { Gson gson = new Gson(); JsonObject object = gson.fromJson(reader, JsonObject.class); arraySize = object.get(DATA_KEY).getAsJsonArray().size(); } } catch (IOException e) { return false; } return arraySize > 1; }
Source:
<code>protected boolean needsEviction(final String token) { boolean needsEviction; <START> needsEviction = isUnknown(token); END> if (!needsEviction) { needsEviction = (getTokenExpiration(token) + TimeUnit.SECONDS.toMillis(tokenEvictionGracePeriod)) <= System.currentTimeMillis(); } return needsEviction; }</code><technical_language>If token is unknown in this case, get IllegalArgumentException subsequent removal is attempted this statement unknown token -> needsEviction. I argue unknown token means evicted. call getTokenExpiration invoked validateToken(), up-front isUnknownToken check is unnecessary (IMO) conclusion is incorrect</technical_language>

Target:
protected boolean needsEviction(final String token) { return ((getTokenExpiration(token) + TimeUnit.SECONDS.toMillis(tokenEvictionGracePeriod)) <= System.currentTimeMillis()); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { toggle(); <START> if(getSlidingMenu().isMenuShowing() && menu.isAdded()) <END> setTitle(((ITitleable)menu).getTitle()); return true; } return false; }</code><technical_language>get brackets this if {}</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { toggle(); if(getSlidingMenu().isMenuShowing() && menu.isAdded()){ setTitle(((ITitleable)menu).getTitle()); } return true; } return false; }
Source:
<code>public int getNumOfChoicesForMsq(String courseId, FeedbackParticipantType generateOptionsFor) { if (generateOptionsFor == FeedbackParticipantType.NONE) { return msqChoices.size(); <START> } else if (generateOptionsFor == FeedbackParticipantType.STUDENTS <END> || generateOptionsFor == FeedbackParticipantType.STUDENTS_EXCLUDING_SELF) { List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); int sizeOfStudentlist = studentList.size(); return generateOptionsFor == FeedbackParticipantType.STUDENTS ? sizeOfStudentlist : sizeOfStudentlist - 1; } else if (generateOptionsFor == FeedbackParticipantType.TEAMS || generateOptionsFor == FeedbackParticipantType.TEAMS_EXCLUDING_SELF) { try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); int sizeOfTeamlist = teamList.size(); return generateOptionsFor == FeedbackParticipantType.TEAMS ? sizeOfTeamlist : sizeOfTeamlist - 1; } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } } else { List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse(courseId); return instructorList.size(); } return 0; }</code><technical_language>of early returns avoid else for this entire method</technical_language>

Target:
public int getNumOfChoicesForMsq(String courseId, FeedbackParticipantType generateOptionsFor) { if (generateOptionsFor == FeedbackParticipantType.NONE) { return msqChoices.size(); } if (generateOptionsFor == FeedbackParticipantType.STUDENTS || generateOptionsFor == FeedbackParticipantType.STUDENTS_EXCLUDING_SELF) { List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); int sizeOfStudentlist = studentList.size(); return generateOptionsFor == FeedbackParticipantType.STUDENTS ? sizeOfStudentlist : sizeOfStudentlist - 1; } if (generateOptionsFor == FeedbackParticipantType.TEAMS || generateOptionsFor == FeedbackParticipantType.TEAMS_EXCLUDING_SELF) { try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); int sizeOfTeamlist = teamList.size(); return generateOptionsFor == FeedbackParticipantType.TEAMS ? sizeOfTeamlist : sizeOfTeamlist - 1; } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } } List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse(courseId); return instructorList.size(); }
Source:
<code>public SimpleHttpServer(HttpServerConfig config, Map<String, HttpHandler> handler) throws IOException { this.config = config; this.service = Executors.newFixedThreadPool( config.threads(), <START> new ThreadFactoryBuilder() <END> .setDaemon(true) .setNameFormat(config.name() + "-%d") .build()); InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", config.port()); server = HttpServer.create(inetSocketAddress, config.backlog()); server.setExecutor(service); for (Entry<String, HttpHandler> entry : handler.entrySet()) { server.createContext(entry.getKey(), entry.getValue()); } if (config.enabled()) { server.start(); } LOG.info("Started admin server on port {}", config.port()); }</code><technical_language>I this handy class</technical_language>

Target:
public SimpleHttpServer(HttpServerConfig config, Map<String, HttpHandler> handler) throws IOException { this.config = config; this.service = Executors.newFixedThreadPool( config.threads(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat(config.name() + "-%d") .build()); InetSocketAddress inetSocketAddress = new InetSocketAddress(config.port()); server = HttpServer.create(inetSocketAddress, config.backlog()); server.setExecutor(service); for (Entry<String, HttpHandler> entry : handler.entrySet()) { server.createContext(entry.getKey(), entry.getValue()); } if (config.enabled()) { server.start(); } LOG.info("Started admin server on port {}", config.port()); }
Source:
<code>public void removeSomeEntriesRemovesThoseEntriesFromEntriesList() { List<BibEntry> allEntries = new ArrayList<>(); BibEntry entry1 = new BibEntry(); BibEntry entry2 = new BibEntry(); BibEntry entry3 = new BibEntry(); allEntries.add(entry1); allEntries.add(entry2); allEntries.add(entry3); database.insertEntries(allEntries); <START> List<BibEntry> entriesToDelete = new ArrayList<>(); <END> entriesToDelete.add(entry1); entriesToDelete.add(entry3); database.removeEntries(entriesToDelete); assertEquals(Collections.singletonList(entry2), database.getEntries()); assertFalse(database.containsEntryWithId(entry1.getId())); assertTrue(database.containsEntryWithId(entry2.getId())); assertFalse(database.containsEntryWithId(entry3.getId())); }</code><technical_language>Arrays.asList</technical_language>

Target:
public void removeSomeEntriesRemovesThoseEntriesFromEntriesList() { BibEntry entry1 = new BibEntry(); BibEntry entry2 = new BibEntry(); BibEntry entry3 = new BibEntry(); List<BibEntry> allEntries = Arrays.asList(entry1, entry2, entry3); database.insertEntries(allEntries); List<BibEntry> entriesToDelete = Arrays.asList(entry1, entry3); database.removeEntries(entriesToDelete); assertEquals(Collections.singletonList(entry2), database.getEntries()); assertFalse(database.containsEntryWithId(entry1.getId())); assertTrue(database.containsEntryWithId(entry2.getId())); assertFalse(database.containsEntryWithId(entry3.getId())); }
Source:
<code><START> public void onApplicationEvent(ContextRefreshedEvent event) { <END> if (!this.listenerRegistered && isAutoStartup()) { doStart(); } }</code><technical_language>Need check event is for this context</technical_language>

Target:
public void onApplicationEvent(ContextRefreshedEvent event) { if (!this.listenerRegisteredOnStartup.getAndSet(true) && isAutoStartup()) { doStart(); } }
Source:
<code>public void run() { for (ReportableEntityType type : ReportableEntityType.values()) { AtomicLong samples = perEntitySamples.computeIfAbsent(type, k -> new AtomicLong(0)); long rate = handlerFactory.getReceivedRate(type); if (rate > 0 || samples.get() > 0) { samples.incrementAndGet(); Sample sample = perEntityStats.computeIfAbsent(type, x -> new ExponentiallyDecayingSample(DEFAULT_SAMPLE_SIZE, DEFAULT_ALPHA)); sample.update(rate); if (samples.get() >= 300) { RecyclableRateLimiter rateLimiter = entityProps.get(type).getRateLimiter(); double suggestedLimit = (MIN_RATE_LIMIT + sample.getSnapshot().getMedian()) * HEADROOM; if (Math.abs(rateLimiter.getRate() - suggestedLimit) > rateLimiter.getRate() * 0.05) { <START> rateLimiter.setRate(suggestedLimit); <END> } } } } }</code><technical_language>resetting rate limit do weird rate limiter? (looked RecyclableRateLimiter code not, asked. do want median * 1.25? want a higher percentile measurement</technical_language>

Target:
public void run() { for (ReportableEntityType type : ReportableEntityType.values()) { AtomicLong samples = perEntitySamples.computeIfAbsent(type, k -> new AtomicLong(0)); EntityProperties props = entityProps.get(type); long rate = props.getTotalReceivedRate(); boolean hasBacklog = props.getTotalBacklogSize() > 0; if (rate > 0 || samples.get() > 0) { samples.incrementAndGet(); Sample stats = updateStats(type, rate); if (samples.get() >= 300) { RecyclableRateLimiter rateLimiter = props.getRateLimiter(); adjustRateLimiter(type, stats, rateLimiter, hasBacklog); } } } }
Source:
<code>public int indexActivities(final String accessToken) { final Collection<AppActivity> activities = new ArrayList<>(); final String username = getAppState(accessToken).getUsername(); for (final RunkeeperActivityItem item : getActivities(accessToken, calculateFetchDate()).getItemsAsList()) { <START> if(!repository.exists(item.getId())) { <END> final AppActivity activity = new AppActivity(item.getId(), username, item.getType(), item.getDate(), item.getDistance(), item.getFormattedDuration()); LOGGER.debug("prepare {}", activity); activities.add(activity); } } LOGGER.info("new activities: {}", activities.size()); if (!activities.isEmpty()) { repository.save(activities); } return activities.size(); }</code><technical_language>Sounds good. refactor for-loop a filtered stream</technical_language>

Target:
public int indexActivities(final String accessToken) { final Collection<AppActivity> activities = new ArrayList<>(); final String username = getAppState(accessToken).getUsername(); getActivities(accessToken, calculateFetchDate()).getItemsAsList().stream() .filter(item -> !repository.exists(item.getId())) .forEach(item -> addActivity(item, username, activities)); LOGGER.info("new activities: {}", activities.size()); if (!activities.isEmpty()) { repository.save(activities); } return activities.size(); }
Source:
<code>private ServiceReference<Marshalling>[] getXmlMarshallers() { <START> String filterString = String.format("(&(kura.service.pid=%s))", "org.eclipse.kura.marshalling.xml.provider"); <END> return ServiceUtil.getServiceReferences(this.bundleContext, Marshalling.class, filterString); }</code><technical_language>Call ComponentUtil.getXmlMarshallers() similar in 2 methods</technical_language>

Target:
private ServiceReference<Marshaller>[] getXmlMarshallers() { String filterString = String.format("(&(kura.service.pid=%s))", "org.eclipse.kura.xml.marshaller.unmarshaller.provider"); return ServiceUtil.getServiceReferences(this.bundleContext, Marshaller.class, filterString); }
Source:
<code>public static Builder overriding(ExecutableElement method) { checkNotNull(method, "method == null"); Set<Modifier> modifiers = method.getModifiers(); if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.STATIC)) { throw new IllegalArgumentException("cannot override method with modifiers: " + modifiers); } String methodName = method.getSimpleName().toString(); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName); methodBuilder.addAnnotation(Override.class); modifiers = new LinkedHashSet<>(modifiers); modifiers.remove(Modifier.ABSTRACT); <START> methodBuilder.addModifiers(modifiers.toArray(new Modifier[modifiers.size()])); <END> for (TypeParameterElement typeParameterElement : method.getTypeParameters()) { methodBuilder.addTypeVariable( TypeVariableName.get((TypeVariable) typeParameterElement.asType())); } methodBuilder.returns(TypeName.get(method.getReturnType())); for (VariableElement parameter : method.getParameters()) { methodBuilder.addParameter(TypeName.get(parameter.asType()), parameter.getSimpleName().toString()); } for (TypeMirror thrownType : method.getThrownTypes()) { methodBuilder.addException(TypeName.get(thrownType)); } return methodBuilder; }</code><technical_language>want overload of addModifiers() takes a Collection</technical_language>

Target:
public static Builder overriding(ExecutableElement method) { checkNotNull(method, "method == null"); Set<Modifier> modifiers = method.getModifiers(); if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.STATIC)) { throw new IllegalArgumentException("cannot override method with modifiers: " + modifiers); } String methodName = method.getSimpleName().toString(); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName); methodBuilder.addAnnotation(Override.class); modifiers = new LinkedHashSet<>(modifiers); modifiers.remove(Modifier.ABSTRACT); methodBuilder.addModifiers(modifiers); for (TypeParameterElement typeParameterElement : method.getTypeParameters()) { methodBuilder.addTypeVariable( TypeVariableName.get((TypeVariable) typeParameterElement.asType())); } methodBuilder.returns(TypeName.get(method.getReturnType())); for (VariableElement parameter : method.getParameters()) { methodBuilder.addParameter(TypeName.get(parameter.asType()), parameter.getSimpleName().toString()); } for (TypeMirror thrownType : method.getThrownTypes()) { methodBuilder.addException(TypeName.get(thrownType)); } return methodBuilder; }
Source:
<code>public void testSupplierSetsAttribute() throws Exception { <START> entity = app.addChild(EntitySpec.create(DataEntity.class) <END> .configure(DataEntity.POLL_PERIOD, 100l) .configure(DataEntity.SENSOR_SUPPLIER_MAP, MutableMap.<AttributeSensor<?>, Supplier<?>>of(stringSensor, new Supplier<String>() { @Override public String get() { return reference.get(); } }))); Entities.startManagement(entity); app.start(ImmutableList.of(loc)); reference.set("new"); Thread.sleep(200l); String value = entity.getAttribute(stringSensor); assertNotNull(value); assertEquals(value, "new"); }</code><technical_language>app.createAndManageChild avoid call startManagement afterwards</technical_language>

Target:
public void testSupplierSetsAttribute() throws Exception { entity = app.createAndManageChild(EntitySpec.create(DataEntity.class) .configure(DataEntity.POLL_PERIOD, 50L) .configure(DataEntity.SENSOR_SUPPLIER_MAP, MutableMap.<AttributeSensor<?>, Supplier<?>>of(stringSensor, new Supplier<String>() { @Override public String get() { return reference.get(); } }))); app.start(ImmutableList.of(loc)); reference.set("new"); EntityTestUtils.assertAttributeEqualsEventually(entity, stringSensor, "new"); }
Source:
<code>public Subscription schedule(final Action0 action, long delayTime, TimeUnit unit) { final long delay = unit.toMillis(delayTime); final Runnable delayLaunch = new Runnable() { @Override public void run() { try { <START> Thread.sleep(delay); <END> } catch (InterruptedException e) { System.err.println("iOS post-delay thread interrupted"); } } }; final Runnable runnable = new Runnable() { @Override public void run() { if (isUnsubscribed()) { return; } action.call(); } }; NSBlockOperation delayOperation = new NSBlockOperation(); NSBlockOperation runOperation = new NSBlockOperation(); delayOperation.addExecutionBlock$(delayLaunch); runOperation.addExecutionBlock$(runnable); runOperation.addDependency$(delayOperation); operationQueue.addOperation$(delayOperation); operationQueue.addOperation$(runOperation); return Subscriptions.empty(); }</code><technical_language>I RoboVM. sleep. For codes: schedule(action1, 5, TimeUnit.SECONDS); schedule(action2, 2, TimeUnit.SECONDS); action2 run in 2 seconds 2 + 5 sceonds</technical_language>

Target:
public Subscription schedule(final Action0 action, long delayTime, TimeUnit unit) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); final NSBlockOperation runOperation = new NSBlockOperation(); executor.schedule(new Runnable() { @Override public void run() { if (isUnsubscribed()) { return; } final Runnable actionRunner = new Runnable() { @Override public void run() { action.call(); } }; runOperation.addExecutionBlock$(actionRunner); operationQueue.addOperation(runOperation); } }, delayTime, unit); return Subscriptions.create(new Action0() { @Override public void call() { runOperation.cancel(); } }); }
Source:
<code>public void setCredentials(String user, String password) { if (user != null && password != null) { Credentials credentials = new UsernamePasswordCredentials(user, password); this.client.getCredentialsProvider().setCredentials( new AuthScope(httpHost.getHostName(), httpHost.getPort()), credentials); <START> } <END> }</code><technical_language>Please retain ability clear credentials calling null username password</technical_language>

Target:
public void setCredentials(String user, String password) { Credentials credentials = null; if (user != null && password != null) credentials = new UsernamePasswordCredentials(user, password); this.client.getCredentialsProvider().setCredentials( new AuthScope(httpHost.getHostName(), httpHost.getPort()), credentials); }
Source:
<code>public Sheet sheet() { try { return new RestSheet( URI.create( <START> new JdkRequest(UriBuilder.fromUri(this.home).build()) <END> .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .method(Request.GET) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath("/page/links/link[@rel='account']/@href") .get(0) ), this.token ); } catch (IOException ex) { throw new IllegalStateException(ex); } }</code><technical_language>this.home is enough</technical_language>

Target:
public Sheet sheet() { try { return new RestSheet( URI.create( new JdkRequest(this.home) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath("/page/links/link[@rel='account']/@href") .get(0) ), this.token ); } catch (IOException ex) { throw new IllegalStateException(ex); } }
Source:
<code>public void conceptListHelper_shouldReturnEmptyListWhenGivenDescriptorIsNullOrEmpty() { List<Concept> list = OpenmrsUtil.conceptListHelper(""); <START> assertTrue(list.size() == 0); <END> list = OpenmrsUtil.conceptListHelper(null); assertTrue(list.size() == 0); }</code><technical_language>List a Collection a defined method check empty not</technical_language>

Target:
public void conceptListHelper_shouldReturnEmptyListWhenGivenDescriptorIsNullOrEmpty() { assertTrue(OpenmrsUtil.conceptListHelper("").isEmpty()); assertTrue(OpenmrsUtil.conceptListHelper(null).isEmpty()); }
Source:
<code>public void shoudAvailableLocalesBeNonEmpty() { List<String> locales = LocaleUtils.getAvailableLocales(); int localesSize = locales.size(); <START> assertTrue(localesSize > 0); <END> }</code><technical_language>assertThat(locales, is(not(empty()))); instead</technical_language>

Target:
public void shoudAvailableLocalesBeNonEmpty() { List<String> locales = LocaleUtils.getAvailableLocales(); assertThat(locales, is(not(empty()))); }
Source:
<code>public Phone setAccount(Account account) { if(((AbstractResource)account).isMaterialized()) { setResourceProperty(ACCOUNT,account); } else{ <START> setMaterializableResourceProperty(ACCOUNT,account); <END> } return this; }</code><technical_language>I setMaterializableResourceProperty handle materialized scenario itself. This means this method simply invoke setMaterializableResourceProperty(ACCOUNT,account); then, internal code of setMaterializableResourceProperty check account is materialized relay setResourceProperty(ACCOUNT,account); internally</technical_language>

Target:
public Phone setAccount(Account account) { setMaterializableResourceProperty(ACCOUNT, account); return this; }
Source:
<code>public SmeltingRecipe build() { <START> checkState(exemplaryResult != null && exemplaryResult != ItemStackSnapshot.NONE, <END> "The result must be specified."); checkState(exemplaryIngredient != null && exemplaryIngredient != ItemStackSnapshot.NONE, "The ingredient must be specified."); checkState(ingredientPredicate != null, "You must specify the ingredient predicate."); checkState(ingredientPredicate.test(exemplaryIngredient), "The ingredient predicate does not allow the specified exemplary ingredient."); checkState(experience >= 0, "The experience must be non-negative."); return new SpongeSmeltingRecipe(exemplaryResult, exemplaryIngredient, ingredientPredicate, experience); }</code><technical_language>this</technical_language>

Target:
public SmeltingRecipe build() { checkState(this.exemplaryResult != null && this.exemplaryResult != ItemStackSnapshot.NONE, "The result must be specified."); checkState(this.exemplaryIngredient != null && this.exemplaryIngredient != ItemStackSnapshot.NONE, "The ingredient must be specified."); checkState(this.ingredientPredicate != null, "You must specify the ingredient predicate."); checkState(this.ingredientPredicate.test(this.exemplaryIngredient), "The ingredient predicate does not allow the specified exemplary ingredient."); checkState(this.experience >= 0, "The experience must be non-negative."); return new SpongeSmeltingRecipe(this.exemplaryResult, this.exemplaryIngredient, this.ingredientPredicate, this.experience); }
Source:
<code>public static void tickEntity(final Consumer<net.minecraft.entity.Entity> consumer, final net.minecraft.entity.Entity entity) { checkArgument(entity instanceof Entity, "Entity %s is not an instance of SpongeAPI's Entity!", entity); checkNotNull(entity, "Cannot capture on a null ticking entity!"); <START> final EntityBridge mixinEntity = (EntityBridge) entity; <END> if (!mixinEntity.bridge$shouldTick()) { return; } final EntityTickContext tickContext = TickPhase.Tick.ENTITY.createPhaseContext().source(entity); try (final EntityTickContext context = tickContext; final Timing entityTiming = ((TimingBridge) entity).bridge$getTimingsHandler() ) { if (entity instanceof OwnershipTrackedBridge) { ((OwnershipTrackedBridge) entity).tracked$getNotifierReference() .ifPresent(context::notifier); ((OwnershipTrackedBridge) entity).tracked$getOwnerReference() .ifPresent(context::owner); } context.buildAndSwitch(); entityTiming.startTiming(); consumer.accept(entity); if (ShouldFire.MOVE_ENTITY_EVENT_POSITION || ShouldFire.ROTATE_ENTITY_EVENT) { SpongeCommonEventFactory.callMoveEntityEvent(entity, context); } } catch (Exception | NoClassDefFoundError e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, tickContext); } }</code><technical_language>mixinEntity -> entityBridge</technical_language>

Target:
public static void tickEntity(final Consumer<net.minecraft.entity.Entity> consumer, final net.minecraft.entity.Entity entity) { checkArgument(entity instanceof Entity, "Entity %s is not an instance of SpongeAPI's Entity!", entity); checkNotNull(entity, "Cannot capture on a null ticking entity!"); final EntityBridge mixinEntity = (EntityBridge) entity; if (!mixinEntity.bridge$shouldTick()) { return; } final EntityTickContext tickContext = TickPhase.Tick.ENTITY.createPhaseContext(PhaseTracker.SERVER).source(entity); try (final EntityTickContext context = tickContext; final Timing entityTiming = ((TimingBridge) entity).bridge$getTimingsHandler() ) { if (entity instanceof OwnershipTrackedBridge) { ((OwnershipTrackedBridge) entity).tracked$getNotifierReference() .ifPresent(context::notifier); ((OwnershipTrackedBridge) entity).tracked$getOwnerReference() .ifPresent(context::owner); } context.buildAndSwitch(); entityTiming.startTiming(); consumer.accept(entity); if (ShouldFire.MOVE_ENTITY_EVENT_POSITION || ShouldFire.ROTATE_ENTITY_EVENT) { SpongeCommonEventFactory.callMoveEntityEvent(entity, context); } } catch (Exception | NoClassDefFoundError e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, tickContext); } }
Source:
<code>private List<FenceProxySourceType> getFenceProxySources() { List<FenceProxySourceType> fenceProxySources = _vds.getFenceProxySources(); if (fenceProxySources == <START> null || <END> fenceProxySources.isEmpty()) { fenceProxySources = FenceProxySourceTypeHelper.parseFromString( Config.<String> getValue(ConfigValues.FenceProxyDefaultPreferences)); } return fenceProxySources; }</code><technical_language>CollectionUtils.isEmpty</technical_language>

Target:
private List<FenceProxySourceType> getFenceProxySources() { List<FenceProxySourceType> fenceProxySources = _vds.getFenceProxySources(); if (CollectionUtils.isEmpty(fenceProxySources)) { fenceProxySources = FenceProxySourceTypeHelper.parseFromString( Config.<String> getValue(ConfigValues.FenceProxyDefaultPreferences)); } return fenceProxySources; }
Source:
<code>private void createNestedRepo(String path) throws IOException { File gitLinkDir = new File(db.getWorkTree(), path); FileUtils.mkdir(gitLinkDir); FileRepositoryBuilder nestedBuilder = new FileRepositoryBuilder(); nestedBuilder.setWorkTree(gitLinkDir); Repository nestedRepo = nestedBuilder.build(); nestedRepo.create(); <START> File readme1 = new File(gitLinkDir, "README1.md"); FileUtils.createNewFile(readme1); PrintWriter writer1 = new PrintWriter(readme1); writer1.print("content"); writer1.close(); <END> File readme2 = new File(gitLinkDir, "README2.md"); FileUtils.createNewFile(readme2); PrintWriter writer2 = new PrintWriter(readme2); writer2.print("content"); writer2.close(); try (Git git = new Git(nestedRepo)) { git.add().addFilepattern(".").call(); git.commit().setMessage("subrepo commit").call(); } catch (GitAPIException e) { throw new RuntimeException(e); } }</code><technical_language>writeTrashFile() shorten this</technical_language>

Target:
private void createNestedRepo(String path) throws IOException { File gitLinkDir = new File(db.getWorkTree(), path); FileUtils.mkdir(gitLinkDir); FileRepositoryBuilder nestedBuilder = new FileRepositoryBuilder(); nestedBuilder.setWorkTree(gitLinkDir); Repository nestedRepo = nestedBuilder.build(); nestedRepo.create(); writeTrashFile(path, "README1.md", "content"); writeTrashFile(path, "README2.md", "content"); try (Git git = new Git(nestedRepo)) { git.add().addFilepattern(".").call(); git.commit().setMessage("subrepo commit").call(); } catch (GitAPIException e) { throw new RuntimeException(e); } }
Source:
<code>private String exportBase64Certificate(PemObject pemObject) throws InternalErrorException { String exportedCert; try { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); <START> Certificate certificate = certFact.generateCertificate(new ByteArrayInputStream(pemObject.getContent())); <END> exportedCert = "-----BEGIN CERTIFICATE-----" + "\n"; exportedCert += Base64.getMimeEncoder().encodeToString(certificate.getEncoded()); exportedCert += "\n" + "-----END CERTIFICATE-----"; } catch (CertificateException ex) { throw new InternalErrorException(ex); } return exportedCert; }</code><technical_language>Unclosed ByteArrayInputStream</technical_language>

Target:
private String exportBase64Certificate(PemObject pemObject) throws InternalErrorException { String exportedCert; try (ByteArrayInputStream bis = new ByteArrayInputStream(pemObject.getContent())) { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); Certificate certificate = certFact.generateCertificate(bis); exportedCert = "-----BEGIN CERTIFICATE-----" + "\n"; exportedCert += Base64.getMimeEncoder().encodeToString(certificate.getEncoded()); exportedCert += "\n" + "-----END CERTIFICATE-----"; } catch (CertificateException | IOException ex) { throw new InternalErrorException(ex); } return exportedCert; }
Source:
<code>RGB acquireCurrentColorSelectionGtk3(long handle, GdkRGBA rgba) { int red = 0; int green = 0; int blue = 0; OS.gtk_color_chooser_get_rgba (handle, rgba); red = (int) (rgba.red * 255); green = (int) (rgba.green * 255); blue = (int) (rgba.blue * 255); <START> rgb = new RGB (red, green, blue); <END> return rgb; }</code><technical_language>assigning 'rgb' a new value, return rgb re-assign rgb get's returned. This duplicate assignment is strange code. Instead consider simply returning a new RGB object touching 'rgb' in this call leave assignment in parent method</technical_language>

Target:
RGB acquireCurrentColorSelectionGtk3(long handle, GdkRGBA rgba) { int red = 0; int green = 0; int blue = 0; OS.gtk_color_chooser_get_rgba (handle, rgba); red = (int) (rgba.red * 255); green = (int) (rgba.green * 255); blue = (int) (rgba.blue * 255); return new RGB (red, green, blue); }
Source:
<code>protected MatchResult matchAndParseHeader(String headerName, String headerValue) { <START> return new MatchResult("<LINK_0>", PrettyPrinterDisplayType.TEXT); <END> }</code><technical_language>test headerName is returning MatchResult This verify if matches</technical_language>

Target:
protected MatchResult matchAndParseHeader(String headerName, String headerValue) { if (headerName.equals(TEST_HEADER_NAME) && headerValue.equals(TEST_HEADER_VALUE)) { return new MatchResult("<LINK_0>", PrettyPrinterDisplayType.TEXT); } else { return null; } }
Source:
<code>public boolean isClosedWithinPastHour() { Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC")); now.add(Calendar.MILLISECOND, <START> (int) (60 * 60 * 1000 * timeZone)); <END> Calendar start = Calendar.getInstance(TimeZone.getTimeZone("UTC")); start.setTime(startTime); Calendar deadline = Calendar.getInstance(TimeZone.getTimeZone("UTC")); deadline.setTime(endTime); long nowMillis = now.getTimeInMillis(); long deadlineMillis = deadline.getTimeInMillis(); long differenceBetweenNowAndDeadline = (deadlineMillis - nowMillis) / (60 * 60 * 1000); return now.after(start) && differenceBetweenNowAndDeadline >= 0 && differenceBetweenNowAndDeadline < 1; }</code><technical_language>This fine previous line</technical_language>

Target:
public boolean isClosedWithinPastHour() { return TimeHelper.isWithinPastHourFromNow(new Date(endTime.getTime() + gracePeriod * 60000)); }
Source:
<code>public final void detectAndSendChanges() { super.detectAndSendChanges(); <START> if (FMLCommonHandler.instance().getSide() == Side.SERVER) { <END> sendUpdateToClient(); sendWidgetsServerData(); } }</code><technical_language>This breaks everything. functions vastly meanings. I need thread on, binary</technical_language>

Target:
public final void detectAndSendChanges() { super.detectAndSendChanges(); if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { sendUpdateToClient(); sendWidgetsServerData(); } }
Source:
<code>public void verifyAsyncMetadataOptionExplicitDisabled() throws Exception { <START> verifyAsyncIs( defaultMetadata, false ); <END> }</code><technical_language>supposed 'syncMetadata', right</technical_language>

Target:
public void verifyAsyncMetadataOptionExplicitDisabled() throws Exception { verifyAsyncIs( syncMetadata, false ); }
Source:
<code>public User createUser(User user, String password) throws APIException { if (user.getUserId() != null) { throw new APIException("This method can be used for only creating new users"); } Context.requirePrivilege(PrivilegeConstants.ADD_USERS); checkPrivileges(user); if (hasDuplicateUsername(user)) { <START> throw new DAOException(String.format("Username %s or system id %s is already in use.", <END> user.getUsername(), user.getSystemId())); } OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId()); return dao.saveUser(user, password); }</code><technical_language>@wisogetnid removing this block</technical_language>

Target:
public User createUser(User user, String password) throws APIException { if (user.getUserId() != null) { throw new APIException("This method can be used for only creating new users"); } Context.requirePrivilege(PrivilegeConstants.ADD_USERS); checkPrivileges(user); if (password == null || password.length() < 1) { throw new APIException("User.creating.password.required", (Object[]) null); } if (hasDuplicateUsername(user)) { throw new DAOException("Username " + user.getUsername() + " or system id " + user.getSystemId() + " is already in use."); } OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId()); return dao.saveUser(user, password); }
Source:
<code>public SdcClientConfigImp() { hostnameVerifier = new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }; javax.net.ssl.TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; try { stx = SSLContext.getInstance("TLS"); stx.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(stx.getSocketFactory()); } catch (Exception e) { <START> System.out.println("SdcClientConfigImp:" + e); <END> } }</code><technical_language>I suppose coding this line account output xxx.log file execution of jetty. Correct</technical_language>

Target:
public SdcClientConfigImp() { hostnameVerifier = new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }; javax.net.ssl.TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; try { stx = SSLContext.getInstance("TLS"); stx.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(stx.getSocketFactory()); } catch (Exception e) { log.error("Error configuring SSL:" + e); } }
Source:
<code>public void testUnoccludeRotationChange() throws Exception { <START> if (!isHandheld() || isUiModeLockedToVrHeadset()) { <END> return; } gotoKeyguard(); mAmWmState.waitForKeyguardShowingAndNotOccluded(mDevice); assertShowingAndNotOccluded(); executeShellCommand(getAmStartCmd("ShowWhenLockedActivity")); mAmWmState.computeState(mDevice, new String[] { "ShowWhenLockedActivity" }); mAmWmState.assertVisibility("ShowWhenLockedActivity", true); setDeviceRotation(1); pressHomeButton(); mAmWmState.waitForKeyguardShowingAndNotOccluded(mDevice); mAmWmState.waitForDisplayUnfrozen(mDevice); mAmWmState.assertSanity(); if (!noHomeScreen()) { mAmWmState.assertHomeActivityVisible(false); } assertShowingAndNotOccluded(); mAmWmState.assertVisibility("ShowWhenLockedActivity", false); }</code><technical_language>this returning already</technical_language>

Target:
public void testUnoccludeRotationChange() throws Exception { if (!isHandheld() || isUiModeLockedToVrHeadset()) { return; } gotoKeyguard(); mAmWmState.waitForKeyguardShowingAndNotOccluded(mDevice); assertShowingAndNotOccluded(); executeShellCommand(getAmStartCmd("ShowWhenLockedActivity")); mAmWmState.computeState(mDevice, new String[] { "ShowWhenLockedActivity" }); mAmWmState.assertVisibility("ShowWhenLockedActivity", true); setDeviceRotation(1); pressHomeButton(); mAmWmState.waitForKeyguardShowingAndNotOccluded(mDevice); mAmWmState.waitForDisplayUnfrozen(mDevice); mAmWmState.assertSanity(); mAmWmState.assertHomeActivityVisible(false); assertShowingAndNotOccluded(); mAmWmState.assertVisibility("ShowWhenLockedActivity", false); }
Source:
<code>public void testGetResultsByID() { String id = "id"; AsyncQueryResultStorage n = new AsyncQueryResultStorage(); n.setId(id); n.setResult(null); Object loaded = n; when(tx.loadObject(any(), any(), any())).thenReturn(loaded); <START> defaultResultStorageEngine.getResultsByID(n.getId()); <END> verify(tx, times(1)).loadObject(any(), any(), any()); }</code><technical_language>skip line 97 Line 102. pass "id" argument</technical_language>

Target:
public void testGetResultsByID() throws SerialException, SQLException { String id = "id"; String test = "test"; AsyncQuery query = new AsyncQuery(); AsyncQueryResult result = new AsyncQueryResult(); query.setId(id); result.setAttachment(new SerialBlob(test.getBytes())); query.setResult(result); when(tx.loadObject(any(), any(), any())).thenReturn(query); byte[] blob = defaultResultStorageEngine.getResultsByID(id); assertEquals(new String(blob), test); verify(tx, times(1)).loadObject(any(), any(), any()); }
Source:
<code>int unsafeCompareTo( Value other ) { ZonedDateTime that = ((DateTimeValue) other).value; int cmp = Long.compare( value.toEpochSecond(), that.toEpochSecond() ); if ( cmp == 0 ) { cmp = value.toLocalTime().getNano() - that.toLocalTime().getNano(); if ( cmp == 0 ) { cmp = value.toLocalDateTime().compareTo( that.toLocalDateTime() ); if ( cmp == 0 ) { ZoneId thisZone = value.getZone(); ZoneId thatZone = that.getZone(); boolean thisIsOffset = thisZone instanceof ZoneOffset; boolean thatIsOffset = thatZone instanceof ZoneOffset; cmp = Boolean.compare( thatIsOffset, thisIsOffset ); <START> if ( cmp == 0 && (thisIsOffset || !areSameZone( thisZone, thatZone ) ) ) <END> { cmp = thisZone.getId().compareTo( thatZone.getId() ); } if ( cmp == 0 ) { cmp = value.getChronology().compareTo( that.getChronology() ); } } } } return cmp; }</code><technical_language>I get checking thisIsOffset explicitly call areSameZone</technical_language>

Target:
int unsafeCompareTo( Value other ) { ZonedDateTime that = ((DateTimeValue) other).value; int cmp = Long.compare( value.toEpochSecond(), that.toEpochSecond() ); if ( cmp == 0 ) { cmp = value.toLocalTime().getNano() - that.toLocalTime().getNano(); if ( cmp == 0 ) { cmp = value.toLocalDateTime().compareTo( that.toLocalDateTime() ); if ( cmp == 0 ) { ZoneId thisZone = value.getZone(); ZoneId thatZone = that.getZone(); boolean thisIsOffset = thisZone instanceof ZoneOffset; boolean thatIsOffset = thatZone instanceof ZoneOffset; cmp = Boolean.compare( thatIsOffset, thisIsOffset ); if ( cmp == 0 && (thisIsOffset || !areSameZone( thisZone, thatZone, thisIsOffset, thatIsOffset ) ) ) { cmp = thisZone.getId().compareTo( thatZone.getId() ); } if ( cmp == 0 ) { cmp = value.getChronology().compareTo( that.getChronology() ); } } } } return cmp; }
Source:
<code>private void updateTable() { fTree.setItemCount(0); if (fTrace == null) { return; } ITmfTrace[] traces; if (fTrace instanceof TmfExperiment) { TmfExperiment experiment = (TmfExperiment) fTrace; traces = experiment.getTraces(); } else { traces = new ITmfTrace[] { fTrace }; } for (ITmfTrace trace : traces) { if (trace instanceof CtfTmfTrace) { TreeItem item = new TreeItem(fTree, SWT.NONE); item.setText(0, trace.getName()); CtfTmfTrace ctfTrace = (CtfTmfTrace) trace; for (String varName : ctfTrace.getEnvNames()) { TreeItem subItem = new TreeItem(item, SWT.NONE); subItem.setText(0, varName); subItem.setText(1, ctfTrace.getEnvValue(varName)); } } } for (TreeColumn column : fTree.getColumns()) { column.pack(); <START> } <END> for (int i = 0; i < fTree.getItemCount(); i++) { fTree.getItem(i).setExpanded(true); } }</code><technical_language>expanded state set pack, pack effect hidden column. set end outer loop (after subitems created, for trace item)</technical_language>

Target:
private void updateTable() { fTree.setItemCount(0); if (fTrace == null) { return; } ITmfTrace[] traces; if (fTrace instanceof TmfExperiment) { TmfExperiment experiment = (TmfExperiment) fTrace; traces = experiment.getTraces(); } else { traces = new ITmfTrace[] { fTrace }; } for (ITmfTrace trace : traces) { if (trace instanceof CtfTmfTrace) { TreeItem item = new TreeItem(fTree, SWT.NONE); item.setText(0, trace.getName()); CtfTmfTrace ctfTrace = (CtfTmfTrace) trace; for (String varName : ctfTrace.getEnvNames()) { TreeItem subItem = new TreeItem(item, SWT.NONE); subItem.setText(0, varName); subItem.setText(1, ctfTrace.getEnvValue(varName)); } } } for (int i = 0; i < fTree.getItemCount(); i++) { fTree.getItem(i).setExpanded(true); } for (TreeColumn column : fTree.getColumns()) { column.pack(); } }
Source:
<code>protected Map<String, Object> updateIntroduction(ParameterParser params, SessionState state) { Map<String, Object> results = new HashMap<String, Object>(); String message; try { String resourceUuid = params.getString("resourceUuid"); String resourceId = this.getContentService().resolveUuid(resourceUuid); String introduction = params.get("addSectionHTML"); introduction = getFormattedText().processFormattedText(introduction, new StringBuilder(), true, true); introduction = introduction.replaceAll("'", "&apos;"); getContentService().addProperty(resourceId, ResourceProperties.PROP_INTRODUCTION, introduction); message = "Resource updated"; state.setAttribute(STATE_CITATION_COLLECTION, null); <START> } catch (IdUnusedException e) { <END> message = e.getMessage(); logger.warn("IdUnusedException in updateCitationList() " + e); } catch (TypeException e) { message = e.getMessage(); logger.warn("TypeException in updateCitationList() " + e); } catch (InUseException e) { message = e.getMessage(); logger.warn("InUseException in updateCitationList() " + e); } catch (PermissionException e) { message = e.getMessage(); logger.warn("PermissionException in updateCitationList() " + e); } catch (ServerOverloadException e) { message = e.getMessage(); logger.warn("ServerOverloadException in updateCitationList() " + e); } catch (VirusFoundException e) { message = e.getMessage(); logger.warn("VirusFoundException in updateCitationList() " + e); } if(message != null && ! message.trim().equals("")) { results.put("message", message); } return results; }</code><technical_language>able catch SakaiException instead if passing stack trace logger.warn(String,Throwable) exception is separate</technical_language>

Target:
protected Map<String, Object> updateIntroduction(ParameterParser params, SessionState state) { Map<String, Object> results = new HashMap<String, Object>(); String message = null; String resourceUuid = params.getString("resourceUuid"); try { String resourceId = this.getContentService().resolveUuid(resourceUuid); String introduction = params.get("addSectionHTML"); introduction = getFormattedText().processFormattedText(introduction, new StringBuilder(), true, true); introduction = introduction.replaceAll("'", "&apos;"); getContentService().addProperty(resourceId, CitationService.PROP_INTRODUCTION, introduction); message = rb.getString("resource.updated"); state.setAttribute(STATE_CITATION_COLLECTION, null); } catch (SakaiException e) { logger.warn("SakaiException in updateIntroduction() for resource UUID: " + resourceUuid, e); } if(message != null && ! message.trim().equals("")) { results.put("message", message); } return results; }
Source:
<code>public void testAllNulState() throws IOException { <START> TmpPath tmp_dir = new TmpPath(); <END> String dir = tmp_dir.getPath(); LocalState ls = new LocalState(dir, true); GlobalStreamId gs_a = new GlobalStreamId("a", "a"); FileOutputStream data = FileUtils.openOutputStream(new File(dir, "12345")); FileOutputStream version = FileUtils.openOutputStream(new File(dir, "12345.version")); Assert.assertNull(ls.get("c")); data.write(new byte[100]); ls.put("a", gs_a); Assert.assertEquals(gs_a, ls.get("a")); }</code><technical_language>Please try resources</technical_language>

Target:
public void testAllNulState() throws IOException { try (TmpPath tmp_dir = new TmpPath()) { GlobalStreamId globalStreamId_a = new GlobalStreamId("a", "a"); String dir = tmp_dir.getPath(); LocalState ls = new LocalState(dir, true); FileUtils.touch(new File(dir, "12345.version")); try (FileOutputStream data = FileUtils.openOutputStream(new File(dir, "12345"))) { Assert.assertNull(ls.get("c")); data.write(new byte[100]); ls.put("a", globalStreamId_a); Assert.assertEquals(globalStreamId_a, ls.get("a")); } } }
Source:
<code><START> public void testValidatesFirstStrandNotLonger() throws IllegalArgumentException { <END> thrown.expect(IllegalArgumentException.class); Hamming.compute("AAAG", "AAA"); }</code><technical_language>need add this exception signature is [unchecked exception](<LINK_0> :)</technical_language>

Target:
public void testValidatesFirstStrandNotLonger() { thrown.expect(IllegalArgumentException.class); Hamming.compute("AAAG", "AAA"); }
Source:
<code>public void blockAllServicesOnDestination(PerunSession sess, int destinationId) throws InternalErrorException, PrivilegeException, DestinationNotExistsException, FacilityNotExistsException { Destination destination = getDestinationById(sess, destinationId); <START> List<Facility> destinationFacilities = perunBl.getFacilitiesManager().getFacilitiesByDestination(sess, destination.getDestination()); <END> boolean isFacilityAdminAtLeastOnce = false; for (Facility facility : destinationFacilities) { if (AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { isFacilityAdminAtLeastOnce = true; } } if (!isFacilityAdminAtLeastOnce && !AuthzResolver.isAuthorized(sess, Role.PERUNADMIN)) { throw new PrivilegeException(sess, "blockAllServicesOnDestination"); } getServicesManagerBl().blockAllServicesOnDestination(sess, destinationId); }</code><technical_language>Again, please BL layer get destination facilities</technical_language>

Target:
public void blockAllServicesOnDestination(PerunSession sess, int destinationId) throws InternalErrorException, PrivilegeException, DestinationNotExistsException, FacilityNotExistsException { Destination destination = getServicesManagerBl().getDestinationById(sess, destinationId); List<Facility> destinationFacilities = perunBl.getFacilitiesManagerBl().getFacilitiesByDestination(sess, destination.getDestination()); boolean isFacilityAdminAtLeastOnce = false; for (Facility facility : destinationFacilities) { if (AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { isFacilityAdminAtLeastOnce = true; } } if (!isFacilityAdminAtLeastOnce && !AuthzResolver.isAuthorized(sess, Role.PERUNADMIN)) { throw new PrivilegeException(sess, "blockAllServicesOnDestination"); } getServicesManagerBl().blockAllServicesOnDestination(sess, destinationId); }