auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<MaintenanceLock> generateMaintenanceLocks() { LOG.debug("generateMaintenanceLocks, entering"); CuObjectCodeActivationGlobal objectCodeGlobal = (CuObjectCodeActivationGlobal) getBusinessObject(); List<MaintenanceLock> maintenanceLocks = new ArrayList<MaintenanceLock>(); for (CuObjectCodeGlobalDetail detail : objectCodeGlobal.getObjectCodeGlobalDetails()) { MaintenanceLock maintenanceLock = new MaintenanceLock(); StringBuffer lockrep = new StringBuffer(); lockrep.append(Account.class.getName() + KFSConstants.Maintenance.AFTER_CLASS_DELIM); lockrep.append(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE + KFSConstants.Maintenance.AFTER_FIELDNAME_DELIM); lockrep.append(detail.getChartOfAccountsCode() + KFSConstants.Maintenance.AFTER_VALUE_DELIM); lockrep.append(KFSPropertyConstants.FISCAL_YEAR + KFSConstants.Maintenance.AFTER_FIELDNAME_DELIM); lockrep.append(detail.getUniversityFiscalYear()); lockrep.append(KFSPropertyConstants.OBJECT_CODE + KFSConstants.Maintenance.AFTER_FIELDNAME_DELIM); lockrep.append(detail.getFinancialObjectCode()); maintenanceLock.setDocumentNumber(objectCodeGlobal.getDocumentNumber()); maintenanceLock.setLockingRepresentation(lockrep.toString()); maintenanceLocks.add(maintenanceLock); } return maintenanceLocks; }

Target:
public List<MaintenanceLock> generateMaintenanceLocks() { LOG.info("generateMaintenanceLocks, entering"); CuObjectCodeActivationGlobal objectCodeGlobal = (CuObjectCodeActivationGlobal) getBusinessObject(); List<MaintenanceLock> maintenanceLocks = new ArrayList(); for (CuObjectCodeGlobalDetail detail : objectCodeGlobal.getObjectCodeGlobalDetails()) { MaintenanceLock maintenanceLock = new MaintenanceLock(); StringBuffer lockrep = new StringBuffer(); lockrep.append(ObjectCode.class.getName() + KFSConstants.Maintenance.AFTER_CLASS_DELIM); lockrep.append(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR + KFSConstants.Maintenance.AFTER_FIELDNAME_DELIM); lockrep.append(detail.getUniversityFiscalYear() + KFSConstants.Maintenance.AFTER_VALUE_DELIM); lockrep.append(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE + KFSConstants.Maintenance.AFTER_FIELDNAME_DELIM); lockrep.append(detail.getChartOfAccountsCode() + KFSConstants.Maintenance.AFTER_VALUE_DELIM); lockrep.append(KFSPropertyConstants.FINANCIAL_OBJECT_CODE + KFSConstants.Maintenance.AFTER_FIELDNAME_DELIM); lockrep.append(detail.getFinancialObjectCode()); maintenanceLock.setDocumentNumber(objectCodeGlobal.getDocumentNumber()); maintenanceLock.setLockingRepresentation(lockrep.toString()); maintenanceLocks.add(maintenanceLock); ObjectCode objectCode = new ObjectCode(); objectCode.setUniversityFiscalYear(detail.getUniversityFiscalYear()); objectCode.setChartOfAccountsCode(detail.getChartOfAccountsCode()); objectCode.setFinancialObjectCode(detail.getFinancialObjectCode()); objectCode.setActive(objectCodeGlobal.getActivate()); if (isInactivatingObjectCode(objectCode)) { maintenanceLocks.addAll(getSubObjectTrickleDownInactivationService().generateTrickleDownMaintenanceLocks(objectCode, getDocumentNumber())); } } return maintenanceLocks; }
Source:
protected void onHandleIntent(Intent intent) { try { handler = new SwrveGcmHandler(this); handler.onHandleIntent(intent); } finally { SwrveGcmBroadcastReceiver.completeWakefulIntent(intent); } }

Target:
protected void onHandleIntent(Intent intent) { try { handler.onHandleIntent(intent, GoogleCloudMessaging.getInstance(this)); } finally { SwrveGcmBroadcastReceiver.completeWakefulIntent(intent); } }
Source:
public void onPushBlock(StreamBlockId streamBlockId, ArrayBuffer<?> dataBuffer) { store(dataBuffer); LinkedList<MessageHeaders> headersListToAck = new LinkedList<MessageHeaders>(); for (int i = 0; i < dataBuffer.size(); i++) { try { headersListToAck.add(headersList.take()); } catch (InterruptedException ie) { logger.error("Interrupted exception while getting message headers from the local blocking queue."); } } ((MessageBusSupport) messageBus).doManualAck(headersListToAck); }

Target:
public void onPushBlock(StreamBlockId streamBlockId, ArrayBuffer<?> dataBuffer) { store(dataBuffer); LinkedList<MessageHeaders> headersListToAck = new LinkedList<MessageHeaders>(); for (int i = 0; i < dataBuffer.size(); i++) { try { headersListToAck.add(headersList.take()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } ((MessageBusSupport) messageBus).doManualAck(headersListToAck); }
Source:
public void getEnabledSendingEndPointByAddress_returnEndpoint_whenNetmaskIsUsed() throws DotDataException { PublishingEndPoint endPoint = createPublishingEndPoint("10", "G03", "Netmask Endpoint", "192.168.1.0/24", "90", "http", true, "123456", true); api.saveEndPoint(endPoint); assertNotNull(api.findEnabledSendingEndPointByAddress("192.168.1.60")); api.deleteEndPointById(endPoint.getId()); }

Target:
public void getEnabledSendingEndPointByAddress_returnEndpoint_whenNetmaskIsUsed() throws DotDataException { PublishingEndPoint endPoint, endPointResult; endPoint = createPublishingEndPoint("10", "G03", "Netmask Endpoint", "192.168.1.0/24", "90", "http", true, "123456", true); api.saveEndPoint(endPoint); validateEndPoint(endPoint, "192.168.1.60"); }
Source:
static List<Class<?>> getClassNamesInJarPackage(ClassLoader loader, String jarName, String packageName) throws MalformedURLException { ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); packageName = packageName.replaceAll("\\.", "/"); JarInputStream jarFileInputStream = null; try { jarFileInputStream = new JarInputStream(new FileInputStream(jarName)); JarEntry jarEntry; while (true) { jarEntry = jarFileInputStream.getNextJarEntry(); if (jarEntry == null) break; if ((jarEntry.getName().startsWith(packageName)) && (jarEntry.getName().endsWith(".class"))) { classes.add(loader.loadClass(jarEntry.getName().replaceAll("/", "\\.").replace(".class", ""))); } } jarFileInputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(jarFileInputStream != null) { jarFileInputStream.close(); } } catch (IOException e) { } } return classes; }

Target:
static List<Class<?>> getClassNamesInJarPackage(ClassLoader loader, String jarName, String packageName) throws MalformedURLException { ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); packageName = packageName.replaceAll("\\.", "/"); JarInputStream jarFileInputStream = null; try { jarFileInputStream = new JarInputStream(new FileInputStream(jarName)); JarEntry jarEntry; while (true) { jarEntry = jarFileInputStream.getNextJarEntry(); if (jarEntry == null) break; if ((jarEntry.getName().startsWith(packageName)) && (jarEntry.getName().endsWith(".class"))) { classes.add(loader.loadClass(jarEntry.getName().replaceAll("/", "\\.").replace(".class", ""))); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if(jarFileInputStream != null) { jarFileInputStream.close(); } } catch (IOException e) { } } return classes; }
Source:
public void testFileIsEmpty() throws Exception { params = new String[1]; params[0] = "/Users/zeinebzhioua/Downloads/a.xml"; new SubmitJobCommand(params).execute(currentContextMock); assertThat(stack.get(0).getMessage(), is("'" + params[0] + "' is empty.")); Mockito.verify(schedulerRestClientMock, times(0)).submitJobArchive(anyString(), anyObject(), anyObject()); throw stack.get(0); }

Target:
public void testFileIsEmpty() throws Exception { params = new String[1]; params[0] = System.getProperty("user.dir") + "/src/test/java/config/empty.xml"; new SubmitJobCommand(params).execute(currentContextMock); assertThat(stack.get(0).getMessage(), is("'" + params[0] + "' is empty.")); Mockito.verify(schedulerRestClientMock, times(0)) .submitJobArchive(anyString(), convertObjectToInputStream(anyObject()), anyMap()); throw stack.get(0); }
Source:
@VisibleForTesting Call<MwQueryResponse<LangLinks>> request(@NonNull Service service, @NonNull PageTitle title, @NonNull final Callback cb) { Call<MwQueryResponse<LangLinks>> call = service.langLinks(title.getPrefixedText()); call.enqueue(new retrofit2.Callback<MwQueryResponse<LangLinks>>() { @Override public void onResponse(Call<MwQueryResponse<LangLinks>> call, Response<MwQueryResponse<LangLinks>> response) { if (response.isSuccessful()) { if (response.body().success()) { cb.success(call, response.body().query().langLinks()); } else if (response.body().hasError()) { String errorTitle = response.body().getError().getTitle(); cb.failure(call, new MwApiException(response.body().getError())); L.e("API error fetching langlinks: " + errorTitle); } } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<MwQueryResponse<LangLinks>> call, Throwable t) { cb.failure(call, t); } }); return call; }

Target:
@VisibleForTesting Call<MwQueryResponse<LangLinks>> request(@NonNull Service service, @NonNull PageTitle title, @NonNull final Callback cb) { Call<MwQueryResponse<LangLinks>> call = service.langLinks(title.getPrefixedText()); call.enqueue(new retrofit2.Callback<MwQueryResponse<LangLinks>>() { @Override public void onResponse(Call<MwQueryResponse<LangLinks>> call, Response<MwQueryResponse<LangLinks>> response) { if (response.isSuccessful()) { if (response.body().success()) { cb.success(call, response.body().query().langLinks()); } else if (response.body().hasError()) { String errorTitle = response.body().getError().getTitle(); cb.failure(call, new MwApiException(response.body().getError())); L.e("API error fetching langlinks: " + errorTitle); } else { cb.failure(call, new IOException("An unknown error occurred.")); } } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<MwQueryResponse<LangLinks>> call, Throwable t) { cb.failure(call, t); } }); return call; }
Source:
protected String render (Object item) { return null; }

Target:
protected String render (Object item) throws InterruptedException { return null; }
Source:
private void mayTriggerRefresh(RepositoryEvent e) { synchronized (repositoriesChanged) { repositoriesChanged.add(e.getRepository()); } if (!isRefreshOnlyWhenActive() || isActive()) { triggerRefresh(); } }

Target:
private void mayTriggerRefresh(RepositoryEvent e) { synchronized (repositoriesChanged) { repositoriesChanged.add(e.getRepository()); } if (!Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.REFESH_ONLY_WHEN_ACTIVE) || isActive()) { triggerRefresh(); } }
Source:
public final void updateEntity() { if (Config.allowExternalTickSpeedup || worldObj == null || worldObj.getTotalWorldTime() != lastUpdate) { lastUpdate = worldObj.getTotalWorldTime(); doUpdate(); if (isProgressTile && !worldObj.isRemote) { int curScaled = getProgressScaled(16); if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { sendTaskProgressPacket(); lastProgressScaled = curScaled; } } } }

Target:
public final void updateEntity() { if (Config.allowExternalTickSpeedup || worldObj.getTotalWorldTime() != lastUpdate) { lastUpdate = worldObj.getTotalWorldTime(); doUpdate(); if (isProgressTile && !worldObj.isRemote) { int curScaled = getProgressScaled(16); if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { sendTaskProgressPacket(); lastProgressScaled = curScaled; } } } }
Source:
private static final void transferStreams(InputStream source, OutputStream destination, long length, String path, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, length >= 0 ? 1 + (int) (length / buffer.length) : 1000); try { synchronized (buffer) { while (true) { int bytesRead = -1; try { bytesRead = source.read(buffer); } catch (IOException e) { String msg = NLS.bind(Messages.failedReadDuringWrite, path); Policy.error(EFS.ERROR_READ, msg, e); } try { if (bytesRead == -1) { destination.close(); break; } destination.write(buffer, 0, bytesRead); } catch (IOException e) { String msg = NLS.bind(Messages.couldNotWrite, path); Policy.error(EFS.ERROR_WRITE, msg, e); } subMonitor.worked(1); } } } finally { Policy.safeClose(source); Policy.safeClose(destination); } }

Target:
private static final void transferStreams(InputStream source, OutputStream destination, long length, String path, IProgressMonitor monitor) throws CoreException { byte[] buffer = new byte[8192]; SubMonitor subMonitor = SubMonitor.convert(monitor, length >= 0 ? 1 + (int) (length / buffer.length) : 1000); try { while (true) { int bytesRead = -1; try { bytesRead = source.read(buffer); } catch (IOException e) { String msg = NLS.bind(Messages.failedReadDuringWrite, path); Policy.error(EFS.ERROR_READ, msg, e); } try { if (bytesRead == -1) { destination.close(); break; } destination.write(buffer, 0, bytesRead); } catch (IOException e) { String msg = NLS.bind(Messages.couldNotWrite, path); Policy.error(EFS.ERROR_WRITE, msg, e); } subMonitor.worked(1); } } finally { Policy.safeClose(source); Policy.safeClose(destination); } }
Source:
public PutMember create(final GroupResource parent, final String id) throws RestApiException { return put.get(); }

Target:
public PutMember create(final GroupResource parent, final String id) throws RestApiException { return new PutMember(put, Url.decode(id)); }
Source:
private void checkWhetherToDisplayUserProjectRegistrationWizard() { ProjectPreferenceSetting projectSetting = preferences .getOrCreateProjectSetting(workspaceName); AbstractHandler newUserWizardHandler = new UserRegistrationWizardDialogHandler(); try { int statusCode = (int) newUserWizardHandler .execute(new ExecutionEvent()); savePreferenceStoreIfNeeded(); if (statusCode == Window.CANCEL && preferences.getUserId() == null) { boolean shouldRegisterAnonymously = MessageDialog.openQuestion( null, "WatchDog not active!", WATCHDOG_UNREGISTERED_WARNING); if (shouldRegisterAnonymously) { makeSilentRegistration(); } else { userProjectRegistrationCancelled = true; preferences.registerProjectUse( WatchDogUtils.getWorkspaceName(), false); } } } catch (ExecutionException exception) { WatchDogLogger.getInstance().logSevere(exception); } }

Target:
private void checkWhetherToDisplayUserProjectRegistrationWizard() { ProjectPreferenceSetting projectSetting = preferences .getOrCreateProjectSetting(workspaceName); if (!WatchDogUtils.isEmpty(preferences.getUserId()) || (projectSetting.startupQuestionAsked && !projectSetting.enableWatchdog)) return; AbstractHandler newUserWizardHandler = new UserRegistrationWizardDialogHandler(); try { int statusCode = (int) newUserWizardHandler .execute(new ExecutionEvent()); savePreferenceStoreIfNeeded(); if (statusCode == Window.CANCEL) { userProjectRegistrationCancelled = true; if (preferences.getUserId() == null || preferences.getOrCreateProjectSetting(workspaceName).projectId == null) { boolean shouldRegisterAnonymously = MessageDialog.openQuestion( null, "WatchDog not active!", WATCHDOG_UNREGISTERED_WARNING); if (shouldRegisterAnonymously) { makeSilentRegistration(); } else { preferences.registerProjectUse( WatchDogUtils.getWorkspaceName(), false); } } } } catch (ExecutionException exception) { WatchDogLogger.getInstance().logSevere(exception); } }
Source:
private void enforceTaskLimits() { int totalRunningTaskCount = 0; int highestRunningTaskCount = 0; Optional<T> highestRunningTaskQuery = Optional.empty(); for (T query : queries.values()) { if (query.isDone()) { continue; } int runningTaskCount = query.getRunningTaskCount(); totalRunningTaskCount += runningTaskCount; if (enqueueQueryWhenTaskLimitExceeded && totalRunningTaskCount > maxTotalRunningTaskCount) { resourceGroupManager.setTaskLimitExceeded(true); } if (runningTaskCount > highestRunningTaskCount) { highestRunningTaskCount = runningTaskCount; highestRunningTaskQuery = Optional.of(query); } } if (enqueueQueryWhenTaskLimitExceeded && totalRunningTaskCount <= maxTotalRunningTaskCount) { resourceGroupManager.setTaskLimitExceeded(false); } runningTaskCount.set(totalRunningTaskCount); if (totalRunningTaskCount > maxTotalRunningTaskCount && highestRunningTaskCount > maxQueryRunningTaskCount && highestRunningTaskQuery.isPresent()) { highestRunningTaskQuery.get().fail(new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Query killed because the cluster is overloaded with too many tasks (%s) and this query was running with the highest number of tasks (%s). %s Otherwise, please try again later.", totalRunningTaskCount, highestRunningTaskCount, TOO_MANY_STAGES_MESSAGE))); queriesKilledDueToTooManyTask.incrementAndGet(); } }

Target:
private void enforceTaskLimits() { int totalRunningTaskCount = 0; int highestRunningTaskCount = 0; Optional<T> highestRunningTaskQuery = Optional.empty(); for (T query : queries.values()) { if (query.isDone()) { continue; } int runningTaskCount = query.getRunningTaskCount(); totalRunningTaskCount += runningTaskCount; if (runningTaskCount > highestRunningTaskCount) { highestRunningTaskCount = runningTaskCount; highestRunningTaskQuery = Optional.of(query); } } runningTaskCount.set(totalRunningTaskCount); if (totalRunningTaskCount > maxTotalRunningTaskCountToKillQuery && highestRunningTaskCount > maxQueryRunningTaskCount && highestRunningTaskQuery.isPresent()) { highestRunningTaskQuery.get().fail(new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Query killed because the cluster is overloaded with too many tasks (%s) and this query was running with the highest number of tasks (%s). %s Otherwise, please try again later.", totalRunningTaskCount, highestRunningTaskCount, TOO_MANY_STAGES_MESSAGE))); queriesKilledDueToTooManyTask.incrementAndGet(); } }
Source:
void completePlayerSetup(boolean asked) { if (asked) { skinLayout = (OoyalaSkinLayout) findViewById(R.id.ooyalaPlayer); PlayerDomain domain1 = new PlayerDomain(domain); Options options = new Options.Builder().setShowNativeLearnMoreButton(false).setShowPromoImage(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(pcode, domain1, options); SkinOptions skinOptions = new SkinOptions.Builder().build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); playerLayoutController.addObserver(this); player.addObserver(this); @SuppressWarnings("unused") OoyalaFreewheelManager fwManager = new OoyalaFreewheelManager(this, skinLayout.getAdView(), player); if (player.setEmbedCode(embedCode)) { } } }

Target:
void completePlayerSetup(boolean asked) { if (asked) { skinLayout = (OoyalaSkinLayout) findViewById(R.id.ooyalaPlayer); PlayerDomain playerDomain = new PlayerDomain(domain); Options options = new Options.Builder().setShowNativeLearnMoreButton(false).setShowPromoImage(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(pcode, playerDomain, options); SkinOptions skinOptions = new SkinOptions.Builder().build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); playerLayoutController.addObserver(this); player.addObserver(this); @SuppressWarnings("unused") OoyalaFreewheelManager fwManager = new OoyalaFreewheelManager(this, skinLayout.getAdView(), player); if (player.setEmbedCode(embedCode)) { } } }
Source:
public void startBackgroundTasks() { try { scheduler.schedule( itunesFileUpdater().withName("iTunes File Updater"), FOUR_AM ); if (!Strings.isNullOrEmpty(localFilesPath)) { scheduler.schedule( new ItunesEpfUpdateTask( new LatestEpfDataSetSupplier(new File(localFilesPath)), contentDeactivator(), contentWriter, log ).withName("iTunes EPF Updater"), FIVE_AM); log.record(infoEntry() .withDescription("iTunes EPF update task installed (%s)", localFilesPath) .withSource(getClass()) ); } else { log.record(infoEntry() .withDescription("iTunes EPF update task not installed", localFilesPath) .withSource(getClass()) ); } } catch (Exception e) { log.record(infoEntry() .withDescription("iTunes EPF update task installed failed") .withSource(getClass()) .withCause(e)); } }

Target:
public void startBackgroundTasks() { checkArgument(!Strings.isNullOrEmpty(localFilesPath)); try { scheduler.schedule( itunesFileUpdater().withName("iTunes File Updater"), ITUNES_FILE_UPDATER ); log.record(infoEntry() .withDescription("iTunes File update task installed (%s)", localFilesPath) .withSource(getClass()) ); scheduler.schedule( new ItunesEpfUpdateTask( new LatestEpfDataSetSupplier(new File(localFilesPath)), contentDeactivator(), contentWriter, log ).withName("iTunes EPF Updater"), ITUNES_EPF_UPDATER ); log.record(infoEntry() .withDescription("iTunes EPF update task installed (%s)", localFilesPath) .withSource(getClass()) ); } catch (Exception e) { log.record(infoEntry() .withDescription("iTunes EPF update task installed failed") .withSource(getClass()) .withCause(e)); } }
Source:
public Builder addPortRange(Integer start, Integer end) { checkState(checkNotNull(start, "start") < checkNotNull(end, "end"), "start of range must be lower than end of range"); this.ports.add(closed(start, end)); return this; }

Target:
public Builder addPortRange(Integer start, Integer end) { checkArgument(checkNotNull(start, "start") < checkNotNull(end, "end"), "start of range must be lower than end of range but was [%d, %d]", start, end); this.ports.add(closed(start, end)); return this; }
Source:
public void testLaunchClusterWithMinDisk() throws RunNodesException { int numNodes = 1; final String name = "node"; ComputeServiceContext context = ContextBuilder.newBuilder("softlayer").credentials(identity, credential) .modules(ImmutableSet.of(new SLF4JLoggingModule(), new SshjSshClientModule())) .build(ComputeServiceContext.class); for(Image image : context.getComputeService().listImages()) { System.out.println(image); } for(Hardware hardware : context.getComputeService().listHardwareProfiles()) { System.out.println(hardware); } Image image = context.getComputeService().getImage("UBUNTU_8_64"); System.out.println(image); for(ComputeMetadata node : context.getComputeService().listNodes()) { System.out.println(node); } TemplateBuilder templateBuilder = context.getComputeService().templateBuilder(); templateBuilder.hardwareId("cpu=1,memory=4096,disk=100,type=SAN"); templateBuilder.imageId("7bcd78dc-eb11-4e1b-8d93-111c62ed5fd1"); templateBuilder.locationId("dal06"); Template template = templateBuilder.build(); template.getOptions().as(SoftLayerTemplateOptions.class).domainName("live.org"); Set<? extends NodeMetadata> nodes = context.getComputeService().createNodesInGroup(name, numNodes, template); assertEquals(numNodes, nodes.size(), "wrong number of nodes"); for (NodeMetadata node : nodes) { logger.debug("Created Node: %s", node); SshClient client = context.utils().sshForNode().apply(node); client.connect(); ExecResponse hello = client.exec("echo hello"); assertEquals(hello.getOutput().trim(), "hello"); context.getComputeService().destroyNode(node.getId()); } }

Target:
public void testLaunchClusterWithMinDisk() throws RunNodesException { int numNodes = 1; final String name = "node"; ComputeServiceContext context = ContextBuilder.newBuilder("softlayer").credentials(identity, credential) .modules(ImmutableSet.of(new SLF4JLoggingModule(), new SshjSshClientModule())) .build(ComputeServiceContext.class); for (ComputeMetadata compute : context.getComputeService().listNodes()) { System.out.println(compute); } TemplateBuilder templateBuilder = context.getComputeService().templateBuilder(); templateBuilder.imageId("CENTOS_6_64"); Template template = templateBuilder.build(); SoftLayerTemplateOptions options = template.getOptions().as(SoftLayerTemplateOptions.class); options.domainName("live.org"); options.blockDevices(ImmutableSet.of(100)); options.tags(ImmutableList.of("jclouds")); Set<? extends NodeMetadata> nodes = context.getComputeService().createNodesInGroup(name, numNodes, template); assertEquals(numNodes, nodes.size(), "wrong number of nodes"); for (NodeMetadata node : nodes) { logger.debug("Created Node: %s", node); SshClient client = context.utils().sshForNode().apply(node); client.connect(); ExecResponse hello = client.exec("mount"); logger.debug(hello.getOutput().trim()); VirtualGuest virtualGuest = context.unwrapApi(SoftLayerApi.class).getVirtualGuestApi() .getVirtualGuest(Long.parseLong(node.getId())); for (VirtualGuestBlockDevice blockDevice : virtualGuest.getVirtualGuestBlockDevices()) { logger.debug(blockDevice.toString()); } context.getComputeService().destroyNode(node.getId()); } }
Source:
private void cancelGeoTagging() { Context context = getContext(); Intent intent = new Intent(context, GeoTagImagesService.class); intent.setAction(GeoTagImagesService.ACTION_CANCEL_GEOTAGGING); getContext().startService(intent); }

Target:
private void cancelGeoTagging() { Context context = getContext(); if (context != null) { Intent intent = new Intent(context, GeoTagImagesService.class); intent.setAction(GeoTagImagesService.ACTION_CANCEL_GEOTAGGING); context.startService(intent); } }
Source:
private void enforceAnyPermissionOf(String... permissions) { for (String permission : permissions) { if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) { return; } } throw new SecurityException( "requires one of the " + String.join(", ", permissions) + " permissions"); }

Target:
private void enforceAnyPermissionOf(String... permissions) { for (String permission : permissions) { if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) { return; } } throw new SecurityException( "Requires one of the following permissions: " + String.join(", ", permissions) + "."); }
Source:
protected List<Location> findSubLocations(Location loc) { if (!loc.hasExtension(AvailabilityZoneExtension.class)) { throw new IllegalStateException("Availability zone extension not supported for location " + loc); } AvailabilityZoneExtension zoneExtension = loc.getExtension(AvailabilityZoneExtension.class); Collection<String> zoneNames = getConfig(AVAILABILITY_ZONE_NAMES); Integer numZones = getConfig(NUM_AVAILABILITY_ZONES); List<Location> subLocations; if (zoneNames == null || zoneNames.isEmpty()) { subLocations = zoneExtension.getSubLocations(numZones); if (numZones != null) { checkArgument(numZones > 0, "numZones must be greater than zero: %s", numZones); if (numZones > subLocations.size()) { throw new IllegalStateException("Number of required zones (" + numZones + ") not satisfied in " + loc + "; only " + subLocations.size() + " available: " + subLocations); } } } else { subLocations = zoneExtension.getSubLocationsByName(StringPredicates.equalToAny(zoneNames), zoneNames.size()); if (zoneNames.size() > subLocations.size()) { throw new IllegalStateException("Number of required zones (" + zoneNames.size() + " - " + zoneNames + ") not satisfied in " + loc + "; only " + subLocations.size() + " available: " + subLocations); } } return subLocations; }

Target:
protected List<Location> findSubLocations(Location loc) { if (!loc.hasExtension(AvailabilityZoneExtension.class)) { throw new IllegalStateException("Availability zone extension not supported for location " + loc); } AvailabilityZoneExtension zoneExtension = loc.getExtension(AvailabilityZoneExtension.class); Collection<String> zoneNames = getConfig(AVAILABILITY_ZONE_NAMES); Integer numZones = getConfig(NUM_AVAILABILITY_ZONES); List<Location> subLocations; if (zoneNames == null || zoneNames.isEmpty()) { if (numZones != null) { subLocations = zoneExtension.getSubLocations(numZones); checkArgument(numZones > 0, "numZones must be greater than zero: %s", numZones); if (numZones > subLocations.size()) { throw new IllegalStateException("Number of required zones (" + numZones + ") not satisfied in " + loc + "; only " + subLocations.size() + " available: " + subLocations); } } else { subLocations = zoneExtension.getAllSubLocations(); } } else { subLocations = zoneExtension.getSubLocationsByName(StringPredicates.equalToAny(zoneNames), zoneNames.size()); if (zoneNames.size() > subLocations.size()) { throw new IllegalStateException("Number of required zones (" + zoneNames.size() + " - " + zoneNames + ") not satisfied in " + loc + "; only " + subLocations.size() + " available: " + subLocations); } } LOG.info("Returning sub-locations: {}", subLocations.size(), Iterables.toString(subLocations)); return subLocations; }
Source:
private void handleKey(Map<CollectionAndKey, Tree> keys, CollectionAndKey collectionAndKey) { if (keys.containsKey(collectionAndKey)) { Tree previousTree = keys.get(collectionAndKey); String indexOrKey = collectionAndKey.keyTree.parent().is(Tree.Kind.ARRAY_DIMENSION) ? "index" : "key"; reportIssue(collectionAndKey.keyTree, String.format("Verify this is the %s that was intended; a value has already been saved for it on line %d.", indexOrKey, previousTree.firstToken().line()), ImmutableList.of(new JavaFileScannerContext.Location("Original value", previousTree)), null); } else { keys.put(collectionAndKey, collectionAndKey.keyTree); } }

Target:
private void handleKey(Map<CollectionAndKey, Tree> keys, CollectionAndKey collectionAndKey) { if (keys.containsKey(collectionAndKey)) { Tree previousTree = keys.get(collectionAndKey); String indexOrKey = collectionAndKey.isArray ? "index" : "key"; reportIssue(collectionAndKey.keyTree, String.format("Verify this is the %s that was intended; a value has already been saved for it on line %d.", indexOrKey, previousTree.firstToken().line()), ImmutableList.of(new JavaFileScannerContext.Location("Original value", previousTree)), null); } else { keys.put(collectionAndKey, collectionAndKey.keyTree); } }
Source:
private void writeReflog(List<ReceiveCommand> commands) { if (getRefLogMessage() == null && !isRefLogIncludingResult()) { return; } ReflogWriter w = refdb.getLogWriter(); for (ReceiveCommand cmd : commands) { if (cmd.getResult() != ReceiveCommand.Result.OK) { continue; } String name = cmd.getRefName(); if (cmd.getType() == ReceiveCommand.Type.DELETE) { try { RefDirectory.delete(w.logFor(name), RefDirectory.levelsIn(name)); } catch (IOException e) { } continue; } String msg = getRefLogMessage(); if (isRefLogIncludingResult()) { String strResult = toResultString(cmd); if (strResult != null) { msg = msg.isEmpty() ? strResult : msg + ": " + strResult; } } PersonIdent ident = getRefLogIdent(); if (ident == null) { ident = new PersonIdent(refdb.getRepository()); } try { w.log(name, cmd.getOldId(), cmd.getNewId(), ident, msg); } catch (IOException e) { } } }

Target:
private void writeReflog(List<ReceiveCommand> commands) { if (isRefLogDisabled()) { return; } PersonIdent ident = getRefLogIdent(); if (ident == null) { ident = new PersonIdent(refdb.getRepository()); } ReflogWriter w = refdb.getLogWriter(); for (ReceiveCommand cmd : commands) { if (cmd.getResult() != ReceiveCommand.Result.OK) { continue; } String name = cmd.getRefName(); if (cmd.getType() == ReceiveCommand.Type.DELETE) { try { RefDirectory.delete(w.logFor(name), RefDirectory.levelsIn(name)); } catch (IOException e) { } continue; } String msg = getRefLogMessage(); if (isRefLogIncludingResult()) { String strResult = toResultString(cmd); if (strResult != null) { msg = msg.isEmpty() ? strResult : msg + ": " + strResult; } } try { w.log(name, cmd.getOldId(), cmd.getNewId(), ident, msg); } catch (IOException e) { } } }
Source:
protected void refreshVisuals() { boolean stack = ((MultiplicityElement) getUMLElement()).getUpper() > 1; getPrimaryShape().setStack(stack); getPrimaryShape().setLayerNumber(1); getPrimaryShape().setXOffSet(2); getPrimaryShape().setYOffSet(-2); super.refreshVisuals(); }

Target:
protected void refreshVisuals() { boolean stack = ((MultiplicityElement) getUMLElement()).getUpper() > 1; getPrimaryShape().setStack(stack); getPrimaryShape().setLayerNumber(LAYER_NUMBER); getPrimaryShape().setXOffSet(X_OFFSET); getPrimaryShape().setYOffSet(Y_OFFSET); getPrimaryShape().setLayerOpacity(LAYER_OPACITY); super.refreshVisuals(); }
Source:
public void poll() { if (!context.getRweSmarthomeSession().isValid()) return; try { rweSmarthomeSession.getNotifications(); lastEventTime = System.currentTimeMillis(); } catch (LogoutNotificationException e) { logger.info("Session expired!" + e.getMessage()); stop(); start(); } catch (RWESmarthomeSessionExpiredException e) { logger.warn("Session expired!" + e.getMessage()); try { rweSmarthomeSession.logon(context.getConfig().getUsername(), context.getConfig().getPassword(), context.getConfig().getHost()); } catch (LoginFailedException e1) { logger.error("Error loging in: " + e1.getMessage()); } catch (SHTechnicalException e1) { logger.error("Error loging in: " + e1.getMessage()); } logger.info("Login successful."); } catch (ConfigurationChangedException e) { logger.warn("Need to restart RWE Smarthome communicator: " + e.getMessage()); stop(); start(); } }

Target:
public void poll() { if(!runPoller) { return; } if (!context.getRweSmarthomeSession().isValid()) { logger.debug("Invalid session, getNotifications aborted."); return; } try { getNotifications(); lastEventTime = System.currentTimeMillis(); } catch (LogoutNotificationException e) { logger.info("Session expired!" + e.getMessage()); stop(); start(); } catch (RWESmarthomeSessionExpiredException e) { logger.info("Session expired!" + e.getMessage()); try { rweSmarthomeSession.logon(context.getConfig().getUsername(), context.getConfig().getPassword(), context.getConfig().getHost()); } catch (LoginFailedException e1) { logger.error("Error logging in with user'" + context.getConfig().getUsername()+ "' to host '" + context.getConfig().getHost() + "': " + e1.getMessage()); } catch (SHTechnicalException e1) { logger.error("Error logging in with user'" + context.getConfig().getUsername()+ "' to host '" + context.getConfig().getHost() + "': " + e1.getMessage()); } logger.info("Login successful."); } catch (ConfigurationChangedException e) { logger.info("Need to restart RWE Smarthome communicator: " + e.getMessage()); stop(); start(); } }
Source:
private static DataSet getIrisDataSet() { DataSet irisDataSet = null; try { if (DataUtilities.downloadFile(remoteUrl, localPath)) log.debug("Data downloaded from {}", remoteUrl); BufferedReader reader = new BufferedReader( new FileReader(new File(localPath))); List<DataSet> data = new ArrayList<DataSet>(); data = reader.lines() .filter(l -> !l.trim().isEmpty()) .map(mapRowToDataSet) .collect(Collectors.toList()); if (reader != null) reader.close(); DataSetIterator iter = new IteratorDataSetIterator(data.iterator(), 150); irisDataSet = iter.next(); } catch (IOException e) { log.error("IO error", e); } return irisDataSet; }

Target:
private static DataSet getIrisDataSet() { DataSet irisDataSet = null; try { File irisData = new ClassPathResource("iris.txt").getFile(); BufferedReader reader = new BufferedReader(new FileReader(irisData)); List<DataSet> data = reader.lines() .filter(l -> !l.trim().isEmpty()) .map(mapRowToDataSet) .collect(Collectors.toList()); if (reader != null) reader.close(); DataSetIterator iter = new IteratorDataSetIterator(data.iterator(), 150); irisDataSet = iter.next(); } catch (IOException e) { log.error("IO error", e); } return irisDataSet; }
Source:
private boolean verifySignature(final String brokerPackageName) { try { final List<X509Certificate> certs = readCertDataForBrokerApp(brokerPackageName); if (certs.size() == 1) { return verifySignatureHash(certs.get(0)); } final X509Certificate singingCert = getSignerCertAndVerifyCertificateChain(certs); return verifySignatureHash(singingCert); } catch (NameNotFoundException e) { Logger.e(TAG, "Broker related package does not exist", "", ADALError.BROKER_PACKAGE_NAME_NOT_FOUND); } catch (NoSuchAlgorithmException e) { Logger.e(TAG, "Digest SHA algorithm does not exists", "", ADALError.DEVICE_NO_SUCH_ALGORITHM); } catch (final AuthenticationException | IOException | GeneralSecurityException e) { Logger.e(TAG, e.getMessage(), "", ADALError.BROKER_VERIFICATION_FAILED, e); } return false; }

Target:
private boolean verifySignature(final String brokerPackageName) { try { final List<X509Certificate> certs = readCertDataForBrokerApp(brokerPackageName); verifySignatureHash(certs); if (certs.size() > 1) { verifyCertificateChain(certs); } return true; } catch (NameNotFoundException e) { Logger.e(TAG, "Broker related package does not exist", "", ADALError.BROKER_PACKAGE_NAME_NOT_FOUND); } catch (NoSuchAlgorithmException e) { Logger.e(TAG, "Digest SHA algorithm does not exists", "", ADALError.DEVICE_NO_SUCH_ALGORITHM); } catch (final AuthenticationException | IOException | GeneralSecurityException e) { Logger.e(TAG, e.getMessage(), "", ADALError.BROKER_VERIFICATION_FAILED, e); } return false; }
Source:
public void removeNoteInterpreterSettingBinding(String user, String noteId) throws IOException { List<String> settingIds = (interpreterBindings.containsKey(noteId) ? interpreterBindings.remove(noteId) : Collections.<String>emptyList()); for (String settingId : settingIds) { InterpreterSetting setting = get(settingId); if (setting != null) { this.removeInterpretersForNote(setting, user, noteId); } } saveToFile(); }

Target:
public void removeNoteInterpreterSettingBinding(String user, String noteId) throws IOException { List<String> settingIds = interpreterBindings.remove(noteId); if (settingIds != null) { for (String settingId : settingIds) { InterpreterSetting setting = get(settingId); if (setting != null) { this.removeInterpretersForNote(setting, user, noteId); } } } saveToFile(); }
Source:
public String setGateWay(String deploymentUrl, String username, String authToken, String friend, String uName, String password, String proxy, boolean register, String ttl) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getGateWayUrl(deploymentUrl, username); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Register", String.valueOf(register)); if (friend != null) { params.add("FriendlyName", friend); } if (uName != null) { params.add("UserName", uName); } if (password != null) { params.add("Password", password); } if (proxy != null) { params.add("Proxy", proxy); } if (ttl != null) { params.add("TTL", ttl); } String response = null; try { response = webResource.accept(MediaType.APPLICATION_XML).post(String.class, params); } catch (Exception e) { logger.error("Exception : ", e); UniformInterfaceException exception = (UniformInterfaceException)e; } return response; }

Target:
public String setGateWay(String deploymentUrl, String username, String authToken, String friend, String uName, String password, String proxy, boolean register, String ttl) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getGateWayUrl(deploymentUrl, username); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Register", String.valueOf(register)); if (friend != null) { params.add("FriendlyName", friend); } if (uName != null) { params.add("UserName", uName); } if (password != null) { params.add("Password", password); } if (proxy != null) { params.add("Proxy", proxy); } if (ttl != null) { params.add("TTL", ttl); } String response = null; try { response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, params); } catch (Exception e) { logger.error("Exception : ", e); UniformInterfaceException exception = (UniformInterfaceException)e; } return response; }
Source:
public void onFlushResults(Set<P> projections, Timestamp lastHandledEventTime) { projectionRepository.store(projections); projectionRepository.projectionStorage().writeLastHandledEventTime(lastHandledEventTime); }

Target:
public void onFlushResults(Set<P> projections, Timestamp lastHandledEventTime) { projectionRepository.store(projections); projectionRepository.projectionStorage() .writeLastHandledEventTime(lastHandledEventTime); projectionRepository.completeCatchUp(); }
Source:
public String getNodesMBeanHistory(@HeaderParam("sessionid") String sessionId, @QueryParam("nodejmxurl") Set<String> nodesJmxUrl, @QueryParam("objectname") String objectName, @QueryParam("attrs") List<String> attrs, @QueryParam("range") String range) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException, NotConnectedException, MalformedObjectNameException, NullPointerException, MBeanException { RMProxyUserInterface rmProxy = checkAccess(sessionId); Map nodesMBeanHistoryMap = new HashMap<String, String>(); for (String nodeJmxUrl : nodesJmxUrl) { nodesMBeanHistoryMap.put(nodeJmxUrl, rmProxy.getNodeMBeanHistory(nodeJmxUrl, objectName, attrs, range)); } return nodesMBeanHistoryMap.toString(); }

Target:
public Map<String, Map<String, Object>> getNodesMBeanHistory(@HeaderParam("sessionid") String sessionId, @QueryParam("nodejmxurl") Set<String> nodesJmxUrl, @QueryParam("objectname") String objectName, @QueryParam("attrs") List<String> attrs, @QueryParam("range") String range) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException, NotConnectedException, MalformedObjectNameException, NullPointerException, MBeanException { RMProxyUserInterface rmProxy = checkAccess(sessionId); return nodesJmxUrl.stream().collect(Collectors.toMap(nodeJmxUrl -> nodeJmxUrl, nodeJmxUrl -> { try { return processHistoryResult(rmProxy.getNodeMBeanHistory(nodeJmxUrl, objectName, attrs, range), range); } catch (Exception e) { throw new RuntimeException(e); } })); }
Source:
public void testExecutableAttributes() throws Exception { FS fs = FS.DETECTED; org.junit.Assume.assumeTrue(fs.getClass().equals(FS_POSIX_Java7.class)); File f = new File(trash, "bla"); assertTrue(f.createNewFile()); assertFalse(fs.canExecute(f)); String umask = readUmask(); if (umask == null) { return; } char others = umask.charAt(umask.length() - 1); boolean badUmask; if (others != '0' && others != '2' && others != '4' && others != '6') { badUmask = true; } else { badUmask = false; } Set<PosixFilePermission> permissions = readPermissions(f); assertTrue(!permissions.contains(PosixFilePermission.OTHERS_EXECUTE)); assertTrue(!permissions.contains(PosixFilePermission.GROUP_EXECUTE)); assertTrue(!permissions.contains(PosixFilePermission.OWNER_EXECUTE)); fs.setExecute(f, true); RepositoryTestCase.fsTick(f); permissions = readPermissions(f); assertTrue("'owner' execute permission not set", permissions.contains(PosixFilePermission.OWNER_EXECUTE)); assertTrue("'group' execute permission not set", permissions.contains(PosixFilePermission.GROUP_EXECUTE)); if (badUmask) { assertFalse("'others' execute permission set", permissions.contains(PosixFilePermission.OTHERS_EXECUTE)); fail("Unexpected umask during test execution: " + umask); } else { assertTrue("'others' execute permission not set", permissions.contains(PosixFilePermission.OTHERS_EXECUTE)); } }

Target:
public void testExecutableAttributes() throws Exception { FS fs = FS.DETECTED; org.junit.Assume.assumeTrue(fs.getClass().equals(FS_POSIX_Java7.class)); File f = new File(trash, "bla"); assertTrue(f.createNewFile()); assertFalse(fs.canExecute(f)); String umask = readUmask(); if (umask == null) return; char others = umask.charAt(umask.length() - 1); boolean badUmask; if (others != '0' && others != '2' && others != '4' && others != '6') { badUmask = true; } else { badUmask = false; } Set<PosixFilePermission> permissions = readPermissions(f); assertTrue(!permissions.contains(PosixFilePermission.OTHERS_EXECUTE)); assertTrue(!permissions.contains(PosixFilePermission.GROUP_EXECUTE)); assertTrue(!permissions.contains(PosixFilePermission.OWNER_EXECUTE)); fs.setExecute(f, true); RepositoryTestCase.fsTick(f); permissions = readPermissions(f); assertTrue("'owner' execute permission not set", permissions.contains(PosixFilePermission.OWNER_EXECUTE)); assertTrue("'group' execute permission not set", permissions.contains(PosixFilePermission.GROUP_EXECUTE)); if (badUmask) { assertFalse("'others' execute permission set", permissions.contains(PosixFilePermission.OTHERS_EXECUTE)); fail("Unexpected umask during test execution: " + umask); } else { assertTrue("'others' execute permission not set", permissions.contains(PosixFilePermission.OTHERS_EXECUTE)); } }
Source:
protected String makeNext() throws InterruptedException, ConsumerTimeoutException { FetchedDataChunk currentDataChunk = null; Iterator<MessageAndOffset> localCurrent = current.get(); if (localCurrent == null || !localCurrent.hasNext()) { if (consumerTimeoutMs < 0) { currentDataChunk = queue.take(); } else { currentDataChunk = queue.poll(consumerTimeoutMs, TimeUnit.MILLISECONDS); if (currentDataChunk == null) { state = State.NOT_READY; throw new ConsumerTimeoutException("consumer timeout in " + consumerTimeoutMs + " ms"); } } if (currentDataChunk == ConsumerConnector.SHUTDOWN_COMMAND) { logger.warn("Now closing the message stream"); queue.offer(currentDataChunk); state = State.DONE; return null; } else { currentTopicInfo = currentDataChunk.topicInfo; if (currentTopicInfo.getConsumedOffset() < currentDataChunk.fetchOffset) { logger.error("consumed offset: " + currentTopicInfo.getConsumedOffset() + " doesn't match fetch offset: " + currentDataChunk.fetchOffset + " for " + currentTopicInfo + ";\n Consumer may lose data"); currentTopicInfo.resetConsumeOffset(currentDataChunk.fetchOffset); } localCurrent = currentDataChunk.messages.getItertor(); current.set(localCurrent); } } MessageAndOffset item = localCurrent.next(); while (item.offset < currentTopicInfo.getConsumedOffset() && localCurrent.hasNext()) { item = localCurrent.next(); } consumedOffset = item.offset; return Util.toEvent(item.message); }

Target:
protected String makeNext() throws InterruptedException, ConsumerTimeoutException { FetchedDataChunk currentDataChunk = null; if (current == null || !current.hasNext()) { if (consumerTimeoutMs < 0) { currentDataChunk = queue.take(); } else { currentDataChunk = queue.poll(consumerTimeoutMs, TimeUnit.MILLISECONDS); if (currentDataChunk == null) { state = State.NOT_READY; throw new ConsumerTimeoutException("consumer timeout in " + consumerTimeoutMs + " ms"); } } if (currentDataChunk == ConsumerConnector.SHUTDOWN_COMMAND) { logger.warn("Now closing the message stream"); queue.offer(currentDataChunk); state = State.DONE; return null; } else { currentTopicInfo = currentDataChunk.topicInfo; if (currentTopicInfo.getConsumedOffset() < currentDataChunk.fetchOffset) { logger.error("consumed offset: " + currentTopicInfo.getConsumedOffset() + " doesn't match fetch offset: " + currentDataChunk.fetchOffset + " for " + currentTopicInfo + ";\n Consumer may lose data"); currentTopicInfo.resetConsumeOffset(currentDataChunk.fetchOffset); } current = currentDataChunk.messages.getItertor(); } } MessageAndOffset item = current.next(); while (item.offset < currentTopicInfo.getConsumedOffset() && current.hasNext()) { item = current.next(); } consumedOffset = item.offset; return Util.toEvent(item.message); }
Source:
public synchronized boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } List<String> sealedReplicas = getSealedReplicas(); if (sealedReplicas == null) { sealedReplicas = new ArrayList<>(); } String partitionId = replicaId.getPartitionId().toPathString(); boolean success = true; if (!isSealed && sealedReplicas.contains(partitionId)) { logger.trace("Removing the partition from sealReplicas list", partitionId); sealedReplicas.remove(partitionId); success = setSealedReplicas(sealedReplicas); } else if (isSealed && !sealedReplicas.contains(partitionId)) { logger.trace("Adding the partition to sealReplicas list", partitionId); sealedReplicas.add(partitionId); success = setSealedReplicas(sealedReplicas); } logger.trace("Set sealed state of partition is completed", partitionId); return success; }

Target:
public boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } synchronized (helixAdministrationLock) { List<String> sealedReplicas = getSealedReplicas(); if (sealedReplicas == null) { sealedReplicas = new ArrayList<>(); } String partitionId = replicaId.getPartitionId().toPathString(); boolean success = true; if (!isSealed && sealedReplicas.contains(partitionId)) { logger.trace("Removing the partition from sealedReplicas list", partitionId); sealedReplicas.remove(partitionId); success = setSealedReplicas(sealedReplicas); } else if (isSealed && !sealedReplicas.contains(partitionId)) { logger.trace("Adding the partition to sealedReplicas list", partitionId); sealedReplicas.add(partitionId); success = setSealedReplicas(sealedReplicas); } logger.trace("Set sealed state of partition is completed", partitionId); return success; } }