auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private List<String> fixMissingIndexes(Map<String, ExecRow> result) throws StandardException { List<String> messages = new LinkedList<>(); DataSet<ExecRow> dataSet = new ControlDataSet<>(result.values().iterator()); PairDataSet dsToWrite = dataSet .map(new IndexTransformFunction(tentativeIndex), null, false, true, "Prepare Index") .index(new KVPairFunction(), false, true, "Add missing indexes"); DataSetWriter writer = dsToWrite.directWriteData() .destConglomerate(tentativeIndex.getIndex().getConglomerate()) .txn(txn) .build(); writer.write(); int i = 0; messages.add(String.format("Create index for the following %d rows from base table %s.%s:", result.size(), schemaName, tableName)); for (Map.Entry<String, ExecRow> entry : result.entrySet()) { if (i >= maxCheckTableErrors) { messages.add("..."); break; } byte[] key = entry.getValue().getKey(); if (tableKeyTemplate.nColumns() > 0) { tableKeyDecoder.set(key, 0, key.length); tableKeyDecoder.decode(tableKeyTemplate); messages.add(tableKeyTemplate.getClone().toString()); } else { messages.add(entry.getKey()); } i++; } return messages; }

Target:
private void fixMissingIndexes(Map<String, ExecRow> result) throws StandardException { List<String> messages = new LinkedList<>(); DataSet<ExecRow> dataSet = new ControlDataSet<>(result.values().iterator()); PairDataSet dsToWrite = dataSet .map(new IndexTransformFunction(tentativeIndex), null, false, true, "Prepare Index") .index(new KVPairFunction(), false, true, "Add missing indexes"); DataSetWriter writer = dsToWrite.directWriteData() .destConglomerate(tentativeIndex.getIndex().getConglomerate()) .txn(txn) .build(); writer.write(); }
Source:
public void testSuccess() { ConcurrentPhaseExecutor phaseExecutor = createConcurrentPhaseExecutor(ImmutableList.of("Q1", "Q2", "Q3"), queryMap, false); phaseExecutor.run(); }

Target:
public void testSuccess() { MockEventClient eventClient = new MockEventClient(); BenchmarkPhaseEvent phaseEvent = createConcurrentPhaseExecutor(false, eventClient).run(false); assertNotNull(phaseEvent); assertBenchmarkPhaseEvent(phaseEvent, SUCCEEDED); List<BenchmarkPhaseEvent> postedEvents = eventClient.getEvents(); assertEquals(postedEvents.size(), 1); assertBenchmarkPhaseEvent(postedEvents.get(0), SUCCEEDED); }
Source:
public double modify(double speed) { if (speed > maxSpeed) { speed = maxSpeed; } if (speed < minSpeed) { speed = minSpeed; } return speed; }

Target:
public double modify(double speed) { return speedCap.limitValue(speed); }
Source:
public void draw(GC gc) { int colorInt = (fColorRGBA != null) ? fColorRGBA.toInt() : OPAQUE.getAlpha(); Color color = getColor(colorInt); for (int i = 0; i < this.fSeriesPoints.size(); i++) { Color prev = gc.getForeground(); int prevAlpha = gc.getAlpha(); gc.setAlpha(colorInt & 0xff); gc.setForeground(color); List<LongPoint> series = fSeriesPoints.get(i); int[] points = new int[series.size() * 2]; for (int point = 0; point < series.size(); point++) { LongPoint longPoint = series.get(point); points[point * 2] = longPoint.x; points[point * 2 + 1] = fBounds.height - (int) ((longPoint.y - fMin) * fScale) + fBounds.y; } gc.drawPolyline(points); gc.setForeground(prev); gc.setAlpha(prevAlpha); } }

Target:
public void draw(GC gc) { int colorInt = (fColorRGBA != null) ? fColorRGBA.toInt() : BLACK.getAlpha(); Color color = getColor(colorInt); for (int i = 0; i < this.fSeriesPoints.size(); i++) { Color prev = gc.getForeground(); int prevAlpha = gc.getAlpha(); gc.setAlpha(colorInt & 0xff); gc.setForeground(color); List<LongPoint> series = fSeriesPoints.get(i); int[] points = new int[series.size() * 2]; for (int point = 0; point < series.size(); point++) { LongPoint longPoint = series.get(point); points[point * 2] = longPoint.x; points[point * 2 + 1] = fBounds.height - (int) ((longPoint.y - fMin) * fScale) + fBounds.y; } gc.drawPolyline(points); gc.setForeground(prev); gc.setAlpha(prevAlpha); } }
Source:
public void run() { WorkDatabasePathHelper.migrateDatabase(mContext); Preferences.migrateLegacyPreferences( mWorkManager.getApplicationContext(), mWorkManager.getWorkDatabase()); IdGenerator.migrateLegacyIdGenerator( mWorkManager.getApplicationContext(), mWorkManager.getWorkDatabase()); Logger.get().debug(TAG, "Performing cleanup operations."); boolean needsScheduling = cleanUp(); if (shouldRescheduleWorkers()) { Logger.get().debug(TAG, "Rescheduling Workers."); mWorkManager.rescheduleEligibleWork(); mWorkManager.getPreferences().setNeedsReschedule(false); } else if (isForceStopped()) { Logger.get().debug(TAG, "Application was force-stopped, rescheduling."); mWorkManager.rescheduleEligibleWork(); } else if (needsScheduling) { Logger.get().debug(TAG, "Found unfinished work, scheduling it."); Schedulers.schedule( mWorkManager.getConfiguration(), mWorkManager.getWorkDatabase(), mWorkManager.getSchedulers()); } mWorkManager.onForceStopRunnableCompleted(); }

Target:
public void run() { WorkDatabasePathHelper.migrateDatabase(mContext); PreferenceUtils.migrateLegacyPreferences(mContext, mWorkManager.getWorkDatabase()); IdGenerator.migrateLegacyIdGenerator(mContext, mWorkManager.getWorkDatabase()); Logger.get().debug(TAG, "Performing cleanup operations."); boolean needsScheduling = cleanUp(); if (shouldRescheduleWorkers()) { Logger.get().debug(TAG, "Rescheduling Workers."); mWorkManager.rescheduleEligibleWork(); mWorkManager.getPreferenceUtils().setNeedsReschedule(false); } else if (isForceStopped()) { Logger.get().debug(TAG, "Application was force-stopped, rescheduling."); mWorkManager.rescheduleEligibleWork(); } else if (needsScheduling) { Logger.get().debug(TAG, "Found unfinished work, scheduling it."); Schedulers.schedule( mWorkManager.getConfiguration(), mWorkManager.getWorkDatabase(), mWorkManager.getSchedulers()); } mWorkManager.onForceStopRunnableCompleted(); }
Source:
public void snapshot(String snapshotName, TableName tableName) throws IOException, SnapshotCreationException, IllegalArgumentException { try { connection.getSession().getInstanceAdminClient() .waitForOperation(snapshotTable(snapshotName, tableName)); } catch (TimeoutException e) { throw new IOException("Timed out waiting for snapshot creation to finish", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting for snapshot creation to finish"); } }

Target:
public void snapshot(String snapshotName, TableName tableName) throws IOException, SnapshotCreationException, IllegalArgumentException { Operation operation = snapshotTable(snapshotName, tableName); try { connection.getSession().getInstanceAdminClient().waitForOperation(operation); } catch (TimeoutException e) { throw new IOException("Timed out waiting for snapshot creation to finish", e); } }
Source:
public InterpreterResult interpretInput(String code, InterpreterContext context) { SparkEnv.set(env); Console.setOut(context.out); ByteArrayOutputStream replOutput = new ByteArrayOutputStream(); out.setInterpreterOutput(replOutput); context.out.clear(); scala.tools.nsc.interpreter.Results.Result res; try { res = interpret(code); Code r = getResultCode(res); if (r == Code.ERROR) { return new InterpreterResult(r, ""); } if (r == Code.INCOMPLETE) { res = interpret(code + "\nprint(\"\")"); r = getResultCode(res); } if (r == Code.INCOMPLETE) { return new InterpreterResult(r, "Incomplete expression"); } else { putLatestVarInResourcePool(context); return new InterpreterResult(Code.SUCCESS); } } catch (Exception e) { logger.info("Interpreter exception", e); return new InterpreterResult(Code.ERROR, InterpreterUtils.getMostRelevantMessage(e)); } finally { try { context.out.setType(InterpreterResult.Type.TEXT); context.out.write(replOutput.toByteArray()); } catch (IOException e) { System.out.println(ExceptionUtils.getStackTrace(e)); } out.setInterpreterOutput(null); } }

Target:
public InterpreterResult interpretInput(String code, InterpreterContext context) { SparkEnv.set(env); Console.setOut(context.out); ByteArrayOutputStream replOutput = new ByteArrayOutputStream(); out.setInterpreterOutput(replOutput); context.out.clear(); try { scala.tools.nsc.interpreter.Results.Result res = interpret(code); Code r = getResultCode(res); if (r == Code.ERROR) { return new InterpreterResult(r, ""); } else if (r == Code.INCOMPLETE) { return new InterpreterResult(r, "Incomplete expression"); } else { putLatestVarInResourcePool(context); return new InterpreterResult(Code.SUCCESS); } } catch (Exception e) { logger.info("Interpreter exception", e); return new InterpreterResult(Code.ERROR, InterpreterUtils.getMostRelevantMessage(e)); } finally { try { context.out.setType(InterpreterResult.Type.TEXT); context.out.write(replOutput.toByteArray()); } catch (IOException e) { logger.error(e.getMessage(), e); } out.setInterpreterOutput(null); } }
Source:
public Optional<WetData> createFrom(DataHolder dataHolder) { if (dataHolder instanceof ItemStack) { ItemStack stack = (ItemStack) dataHolder; if (stack.getItem().equals(ItemTypes.SPONGE)) { SpongeWetData data = new SpongeWetData(stack.getItemDamage() == 1); return Optional.<WetData>of(data); } } else if (dataHolder instanceof EntityWolf) { EntityWolf wolf = (EntityWolf) dataHolder; SpongeWetData data = new SpongeWetData(wolf.isWet()); return Optional.<WetData>of(data); } return Optional.absent(); }

Target:
public Optional<WetData> createFrom(DataHolder dataHolder) { if (dataHolder instanceof ItemStack) { ItemStack stack = (ItemStack) dataHolder; if (stack.getItem().equals(ItemTypes.SPONGE)) { SpongeWetData data = new SpongeWetData(stack.getItemDamage() == 1); return Optional.<WetData>of(data); } } else if (dataHolder instanceof EntityWolf) { EntityWolf wolf = (EntityWolf) dataHolder; SpongeWetData data = new SpongeWetData(wolf.isWet()); return Optional.<WetData>of(data); } return Optional.empty(); }
Source:
private Collection<Pair<String, String>> parseFeatures(String[] features) throws InfrastructureException { Map<String, Pair<String, String>> featuresNameVersion = new HashMap<>(); for (String feature : features) { String[] featureAndVersion = feature.split("/", 2); if (featureAndVersion.length != 2 || featureAndVersion[0].isEmpty() || featureAndVersion[1] .isEmpty()) { throw new InfrastructureException( "Features format is illegal. Problematic feature entry:" + feature); } String key = featureAndVersion[0] + '/' + featureAndVersion[1]; if (featuresNameVersion.containsKey(key)) { throw new InfrastructureException( format("Invalid Workspace.Next configuration: feature %s is duplicated", key)); } featuresNameVersion.put(key, Pair.of(featureAndVersion[0], featureAndVersion[1])); } return featuresNameVersion.values(); }

Target:
private Collection<Pair<String, String>> parseFeatures(String[] features) throws InfrastructureException { Map<String, Pair<String, String>> featuresNameVersion = new HashMap<>(); for (String feature : features) { String[] featureAndVersion = feature.split("/"); if (featureAndVersion.length != 2 || featureAndVersion[0].isEmpty() || featureAndVersion[1].isEmpty()) { throw new InfrastructureException( "Features format is illegal. Problematic feature entry:" + feature); } String key = featureAndVersion[0] + '/' + featureAndVersion[1]; if (featuresNameVersion.containsKey(key)) { throw new InfrastructureException( format("Invalid Workspace.Next configuration: feature %s is duplicated", key)); } featuresNameVersion.put(key, Pair.of(featureAndVersion[0], featureAndVersion[1])); } return featuresNameVersion.values(); }
Source:
public Tuple next() throws IOException { if (fragments == null) { return null; } while(scanIt.hasNext()) { Tuple outTuple = new VTuple(outColumnNum); Tuple t = scanIt.next(); projector.eval(t, outTuple); outTuple.setOffset(t.getOffset()); return outTuple; } return null; }

Target:
public Tuple next() throws IOException { if (fragments == null) { return null; } Tuple tuple; Tuple outTuple = new VTuple(outColumnNum); if (!plan.hasQual()) { if ((tuple = scanner.next()) != null) { projector.eval(tuple, outTuple); outTuple.setOffset(tuple.getOffset()); return outTuple; } else { return null; } } else { while ((tuple = scanner.next()) != null) { if (qual.eval(tuple).isTrue()) { projector.eval(tuple, outTuple); return outTuple; } } return null; } }
Source:
public void processFiles(RuleSetFactory ruleSetFactory, List<DataSource> files, RuleContext ctx, List<Renderer> renderers) { RuleSets rs = createRuleSets(ruleSetFactory, ctx.getReport()); configuration.getAnalysisCache().checkValidity(rs, configuration.getClassLoader()); SourceCodeProcessor processor = new SourceCodeProcessor(configuration); for (DataSource dataSource : files) { String niceFileName = filenameFrom(dataSource); runAnalysis(new PmdRunnable(dataSource, niceFileName, renderers, ctx, rs, processor)); } for (DataSource dataSource : files) { if (dataSource instanceof ZipDataSource) { IOUtils.closeQuietly((ZipDataSource) dataSource); } } renderReports(renderers, ctx.getReport()); collectReports(renderers); }

Target:
public void processFiles(RuleSetFactory ruleSetFactory, List<DataSource> files, RuleContext ctx, List<Renderer> renderers) { RuleSets rs = createRuleSets(ruleSetFactory, ctx.getReport()); configuration.getAnalysisCache().checkValidity(rs, configuration.getClassLoader()); SourceCodeProcessor processor = new SourceCodeProcessor(configuration); for (DataSource dataSource : files) { String realFileName = dataSource.getNiceFileName(false, null); runAnalysis(new PmdRunnable(dataSource, realFileName, renderers, ctx, rs, processor)); } renderReports(renderers, ctx.getReport()); collectReports(renderers); for (DataSource dataSource : files) { IOUtils.closeQuietly(dataSource); } }
Source:
public Map<String, Set<String>> getGlobalTags() { Map<String, Set<String>> tags = new HashMap<>(); List<String> globalTagsLines = DatadogUtilities.linesToList(globalTags); for (String globalTagsLine : globalTagsLines) { List<String> tagList = DatadogUtilities.cstrToList(globalTagsLine); if (tagList.isEmpty()) { continue; } for (int i = 1; i < tagList.size(); i++) { String[] tagItem = tagList.get(i).split(":"); if(tagItem.length == 2) { String tagName = tagItem[0]; String tagValue = tagItem[1]; Set<String> tagValues = tags.containsKey(tagName) ? tags.get(tagName) : new HashSet<String>(); tagValues.add(tagValue.toLowerCase()); tags.put(tagName, tagValues); } } } return tags; }

Target:
public String getGlobalTags() { return globalTags; }
Source:
public void performHaResevationCheck() { log.debugFormat("HA Reservation check timer entered."); List<VDSGroup> clusters = DbFacade.getInstance().getVdsGroupDao().getAll(); if (clusters != null) { for (VDSGroup cluster : clusters) { if (cluster.supportsHaReservation()) { List<VDS> returnedFailedHosts = new ArrayList<VDS>(); boolean status = new HaReservationHandling().checkHaReservationStatusForCluster(cluster, returnedFailedHosts); if (!status) { AuditLogableBase logable = new AuditLogableBase(); logable.setVdsGroupId(cluster.getId()); logable.addCustomValue("ClusterName", cluster.getName()); StringBuilder failedHostsStr = new StringBuilder(); int commaCount = returnedFailedHosts.size() - 1; for (VDS host : returnedFailedHosts) { failedHostsStr.append(host.getName()); if (commaCount > 0) { failedHostsStr.append(", "); commaCount--; } } logable.addCustomValue("Hosts", failedHostsStr.toString()); AlertDirector.Alert(logable, AuditLogType.CLUSTER_ALERT_HA_RESERVATION); } } } } }

Target:
public void performHaResevationCheck() { log.debugFormat("HA Reservation check timer entered."); List<VDSGroup> clusters = DbFacade.getInstance().getVdsGroupDao().getAll(); if (clusters != null) { HaReservationHandling haReservationHandling = new HaReservationHandling(); for (VDSGroup cluster : clusters) { if (cluster.supportsHaReservation()) { List<VDS> returnedFailedHosts = new ArrayList<VDS>(); boolean status = haReservationHandling.checkHaReservationStatusForCluster(cluster, returnedFailedHosts); if (!status) { AuditLogableBase logable = new AuditLogableBase(); logable.setVdsGroupId(cluster.getId()); logable.addCustomValue("ClusterName", cluster.getName()); String failedHostsStr = StringUtils.join(returnedFailedHosts, ", "); logable.addCustomValue("Hosts", failedHostsStr); AlertDirector.Alert(logable, AuditLogType.CLUSTER_ALERT_HA_RESERVATION); } } } } }
Source:
public static void checkAndEnableBluetooth(Context context, BluetoothAdapter adapter) throws BluetoothNotEnabledException, BluetoothNotSupportedException { if (adapter != null) { if (!adapter.isEnabled()) { Toaster.iToast(context, R.string.enable_bluetooth); boolean enableStarted = adapter.enable(); boolean enabled = false; if (enableStarted) { int retrySeconds = 5; int retryPauseMS = 500; int retries = (retrySeconds * 1000) / retryPauseMS; int retry = 0; do { try { Thread.sleep(retryPauseMS); } catch (InterruptedException e) { } enabled = adapter.isEnabled(); } while (!enabled && retry++ < retries); } if (!enabled) { throw new BluetoothNotEnabledException(); } } } else { throw new BluetoothNotSupportedException(); } }

Target:
public static void checkAndEnableBluetooth(Context context, BluetoothAdapter adapter) throws BluetoothNotEnabledException, BluetoothNotSupportedException { if (adapter != null) { if (!adapter.isEnabled()) { Toaster.iToast(context, R.string.enable_bluetooth); boolean enableStarted = adapter.enable(); boolean enabled = false; if (enableStarted) { int retries = (ENABLE_CHECK_RETRY_SECONDS * 1000) / ENABLE_CHECK_RETRY_PAUSE_MILLISECONDS; int retry = 0; do { try { Thread.sleep(ENABLE_CHECK_RETRY_PAUSE_MILLISECONDS); } catch (InterruptedException e) { } enabled = adapter.isEnabled(); } while (!enabled && retry++ < retries); } if (!enabled) { throw new BluetoothNotEnabledException(); } } } else { throw new BluetoothNotSupportedException(); } }
Source:
public void testLaunchClusterWithDomainName() 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 computeMetadata : context.getComputeService().listNodes()) { System.out.println(computeMetadata); } TemplateBuilder templateBuilder = context.getComputeService().templateBuilder(); Template template = templateBuilder.build(); SoftLayerTemplateOptions options = template.getOptions().as(SoftLayerTemplateOptions.class); options.domainName("live.org"); 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()); context.getComputeService().destroyNode(node.getId()); } }

Target:
public void testLaunchClusterWithDomainName() throws RunNodesException { int numNodes = 1; final String name = "node"; Template template = view.getComputeService().templateBuilder().build(); SoftLayerTemplateOptions options = template.getOptions().as(SoftLayerTemplateOptions.class); options.domainName("live.org"); options.tags(ImmutableList.of("jclouds")); Set<? extends NodeMetadata> nodes = view.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 = view.utils().sshForNode().apply(node); client.connect(); ExecResponse hello = client.exec("mount"); logger.debug(hello.getOutput().trim()); view.getComputeService().destroyNode(node.getId()); } }
Source:
public void onActivate(ActivateEvent event, EntityRef entity) { LASTeam baseTeamComponent = entity.getComponent(LASTeam.class); EntityRef player = event.getInstigator(); CharacterHeldItemComponent characterHeldItemComponent = player.getComponent(CharacterHeldItemComponent.class); EntityRef heldItem = characterHeldItemComponent.selectedItem; if (baseTeamComponent.team.equals(baseTeamComponent.RED) && heldItem.hasComponent(FlagComponent.class) && heldItem.getComponent(LASTeam.class).team.equals("black")) { score.getComponent(ScoreComponent.class).redScore++; } if (baseTeamComponent.team.equals(baseTeamComponent.BLACK) && heldItem.hasComponent(FlagComponent.class) && heldItem.getComponent(LASTeam.class).team.equals("red")) { score.getComponent(ScoreComponent.class).blackScore++; } }

Target:
public void onActivate(ActivateEvent event, EntityRef entity) { LASTeamComponent baseTeamComponent = entity.getComponent(LASTeamComponent.class); EntityRef player = event.getInstigator(); CharacterHeldItemComponent characterHeldItemComponent = player.getComponent(CharacterHeldItemComponent.class); if (characterHeldItemComponent != null) { EntityRef heldItem = characterHeldItemComponent.selectedItem; if (baseTeamComponent.team.equals(baseTeamComponent.RED) && heldItem.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(BLACK_FLAG_URI)) { redScore++; } if (baseTeamComponent.team.equals(baseTeamComponent.BLACK) && heldItem.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(RED_FLAG_URI)) { blackScore++; } } }
Source:
private void bindDataService() { String packageName = getDataServicePackageName(); String className = getDataServiceClassName(); if (TextUtils.isEmpty(packageName)) { loge("Can't find the binding package"); return; } if (TextUtils.equals(packageName, mTargetBindingPackageName)) { if (DBG) log("Service " + packageName + " already bound or being bound."); return; } revokePermissionsFromUnusedDataServices(); if (mIDataService != null && mIDataService.asBinder().isBinderAlive()) { try { mIDataService.removeDataServiceProvider(mPhone.getPhoneId()); } catch (RemoteException e) { loge("Cannot remove data service provider. " + e); } mPhone.getContext().unbindService(mServiceConnection); } grantPermissionsToService(packageName); try { mServiceConnection = new CellularDataServiceConnection(); ComponentName cm = new ComponentName(packageName, className); if (!mPhone.getContext().bindService( new Intent(DataService.SERVICE_INTERFACE).setComponent(cm), mServiceConnection, Context.BIND_AUTO_CREATE)) { loge("Cannot bind to the data service."); return; } mTargetBindingPackageName = packageName; } catch (Exception e) { loge("Cannot bind to the data service. Exception: " + e); } }

Target:
private void bindDataService() { Intent intent = null; String packageName = getDataServicePackageName(); String className = getDataServiceClassName(); if (TextUtils.isEmpty(packageName)) { loge("Can't find the binding package"); return; } if (TextUtils.isEmpty(className)) { intent = new Intent(DataService.SERVICE_INTERFACE); intent.setPackage(packageName); } else { ComponentName cm = new ComponentName(packageName, className); intent = new Intent(DataService.SERVICE_INTERFACE).setComponent(cm); } if (TextUtils.equals(packageName, mTargetBindingPackageName)) { if (DBG) log("Service " + packageName + " already bound or being bound."); return; } revokePermissionsFromUnusedDataServices(); if (mIDataService != null && mIDataService.asBinder().isBinderAlive()) { try { mIDataService.removeDataServiceProvider(mPhone.getPhoneId()); } catch (RemoteException e) { loge("Cannot remove data service provider. " + e); } mPhone.getContext().unbindService(mServiceConnection); } grantPermissionsToService(packageName); try { mServiceConnection = new CellularDataServiceConnection(); if (!mPhone.getContext().bindService( intent, mServiceConnection, Context.BIND_AUTO_CREATE)) { loge("Cannot bind to the data service."); return; } mTargetBindingPackageName = packageName; } catch (Exception e) { loge("Cannot bind to the data service. Exception: " + e); } }
Source:
public String getMeetingUrl() { String url = getBoshURL(); String room = getRoomName(); if(url == null || room == null) { return null; } url = url.substring(0, url.indexOf("http-bind?")); room = room.substring(0, room.indexOf("@")); return url + room; }

Target:
public String getMeetingUrl() { String url = getBoshURL(); String room = getRoomName(); if(url == null || room == null) { return null; } url = url.substring(0, url.indexOf("/http-bind")); room = room.substring(0, room.indexOf("@")); return url + "/" + room; }
Source:
public boolean replaces(LookupExtractorFactoryContainer other) { if (version == null && other.getVersion() == null) { return !this.lookupExtractorFactory.replaces(other.getLookupExtractorFactory()); } if (version == null && other.getVersion() != null) { return false; } if (version != null && other.getVersion() == null) { return true; } return version.compareTo(other.getVersion()) > 0; }

Target:
public boolean replaces(LookupExtractorFactoryContainer other) { if (version == null && other.getVersion() == null) { return this.lookupExtractorFactory.replaces(other.getLookupExtractorFactory()); } return VERSION_COMPARATOR.compare(version, other.getVersion()) > 0; }
Source:
public void testMultipleStrategies() { DarkClusterConfigMap configMap = new DarkClusterConfigMap(); DarkClusterStrategyNameArray multiplierStrategyTypeArray = new DarkClusterStrategyNameArray(); multiplierStrategyTypeArray.add(DarkClusterStrategyName.RELATIVE_TRAFFIC); multiplierStrategyTypeArray.add(DarkClusterStrategyName.CONSTANT_QPS); DarkClusterConfig config = new DarkClusterConfig() .setMultiplierStrategyList(multiplierStrategyTypeArray); configMap.put(DARK_CLUSTER_KEY, config); config.setMultiplier(0.0f); config.setDispatcherOutboundTargetRate(0); config.setDispatcherOutboundMaxRate(Integer.MAX_VALUE); DarkClusterConfigMap expectedConfigMap = new DarkClusterConfigMap(); DarkClusterConfig expectedConfig = new DarkClusterConfig(config.data()); expectedConfig.setMultiplier(0); expectedConfigMap.put(DARK_CLUSTER_KEY, expectedConfig); DarkClusterConfigMap resultConfigMap = DarkClustersConverter.toConfig(DarkClustersConverter.toProperties(configMap)); Assert.assertEquals(resultConfigMap, expectedConfigMap); Assert.assertEquals(resultConfigMap.get(DARK_CLUSTER_KEY).getMultiplierStrategyList().get(0), DarkClusterStrategyName.RELATIVE_TRAFFIC, "expected first strategy to be RELATIVE_TRAFFIC"); Assert.assertEquals(resultConfigMap.get(DARK_CLUSTER_KEY).getMultiplierStrategyList().get(1), DarkClusterStrategyName.CONSTANT_QPS, "expected first strategy to be CONSTANT_QPS"); }

Target:
public void testMultipleStrategies() { DarkClusterConfigMap configMap = new DarkClusterConfigMap(); DarkClusterStrategyNameArray darkClusterStrategyNameArray = new DarkClusterStrategyNameArray(); darkClusterStrategyNameArray.add(DarkClusterStrategyName.RELATIVE_TRAFFIC); darkClusterStrategyNameArray.add(DarkClusterStrategyName.CONSTANT_QPS); DarkClusterConfig config = new DarkClusterConfig() .setDarkClusterStrategyPrioritizedList(darkClusterStrategyNameArray); configMap.put(DARK_CLUSTER_KEY, config); config.setMultiplier(DARK_CLUSTER_DEFAULT_MULTIPLIER); config.setDispatcherOutboundTargetRate(DARK_CLUSTER_DEFAULT_TARGET_RATE); config.setDispatcherOutboundMaxRate(DARK_CLUSTER_DEFAULT_MAX_RATE); DarkClusterConfigMap expectedConfigMap = new DarkClusterConfigMap(); DarkClusterConfig expectedConfig = new DarkClusterConfig(config.data()); expectedConfig.setMultiplier(0); expectedConfigMap.put(DARK_CLUSTER_KEY, expectedConfig); DarkClusterConfigMap resultConfigMap = DarkClustersConverter.toConfig(DarkClustersConverter.toProperties(configMap)); Assert.assertEquals(resultConfigMap, expectedConfigMap); Assert.assertEquals(resultConfigMap.get(DARK_CLUSTER_KEY).getDarkClusterStrategyPrioritizedList().get(0), DarkClusterStrategyName.RELATIVE_TRAFFIC, "expected first strategy to be RELATIVE_TRAFFIC"); Assert.assertEquals(resultConfigMap.get(DARK_CLUSTER_KEY).getDarkClusterStrategyPrioritizedList().get(1), DarkClusterStrategyName.CONSTANT_QPS, "expected first strategy to be CONSTANT_QPS"); }
Source:
public CommonTemplate( Metacard metacard, Map<String, List<Serializable>> securityAttributes) { this.id = safeGet(metacard, Core.ID, String.class); this.title = safeGet(metacard, Core.TITLE, String.class); this.description = safeGet(metacard, Core.DESCRIPTION, String.class); this.created = safeGet(metacard, Core.CREATED, Date.class); this.modified = safeGet(metacard, Core.MODIFIED, Date.class); this.owner = safeGet(metacard, Core.METACARD_OWNER, String.class); this.accessIndividuals = securityAttributes.get(Security.ACCESS_INDIVIDUALS); this.accessGroups = securityAttributes.get(Security.ACCESS_GROUPS); }

Target:
public CommonTemplate(Metacard metacard, Map<String, List<Serializable>> securityAttributes) { this.id = safeGet(metacard, Core.ID, String.class); this.title = safeGet(metacard, Core.TITLE, String.class); this.description = safeGet(metacard, Core.DESCRIPTION, String.class); this.created = safeGet(metacard, Core.CREATED, Date.class); this.modified = safeGet(metacard, Core.MODIFIED, Date.class); this.owner = safeGet(metacard, Core.METACARD_OWNER, String.class); this.accessIndividuals = securityAttributes.getOrDefault(Security.ACCESS_INDIVIDUALS, new ArrayList<>()); this.accessGroups = securityAttributes.getOrDefault(Security.ACCESS_GROUPS, new ArrayList<>()); }
Source:
public int read() throws IOException { synchronized ( InfinispanJF.this ) { if ( closed ) { throw new IOException( "Joint: " + jointIdx + "(" + originalThreadName + "): Cannot read from closed stream!" ); } } if ( block.getBuffer().position() == block.getBuffer().limit() ) { try { FileBlock next = filesystem.getNextBlock( block ); block = next; } catch ( final InterruptedException e) { return -1; } } if ( block.isEOF() ) { return -1; } final int result = block.getBuffer().get(); read++; return result & 0xff; }

Target:
public int read() throws IOException { synchronized ( InfinispanJF.this ) { if ( closed ) { throw new IOException( "Joint: " + jointIdx + "(" + originalThreadName + "): Cannot read from closed stream!" ); } } if ( block.getBuffer().position() == block.getBuffer().limit() ) { if ( block.isEOF() ) { return -1; } try { FileBlock next = filesystem.getNextBlock( block, metadata ); block = next; if ( block == null ) { return -1; } } catch ( final IOException e ) { return -1; } } final int result = block.getBuffer().get(); read++; return result & 0xff; }
Source:
private void repairIndexRows(Map<byte[], List<Mutation>> indexMutationMap, List<Mutation> indexRowsToBeDeleted, IndexToolVerificationResult verificationResult) throws IOException { try { int batchSize = 0; List<Mutation> indexUpdates = new ArrayList<Mutation>(maxBatchSize); for (List<Mutation> mutationList : indexMutationMap.values()) { indexUpdates.addAll(mutationList); batchSize += mutationList.size(); if (batchSize >= maxBatchSize) { ungroupedAggregateRegionObserver.checkForRegionClosing(); region.batchMutate(indexUpdates.toArray(new Mutation[indexUpdates.size()]), HConstants.NO_NONCE, HConstants.NO_NONCE); batchSize = 0; indexUpdates = new ArrayList<Mutation>(maxBatchSize); } } if (batchSize > 0) { ungroupedAggregateRegionObserver.checkForRegionClosing(); region.batchMutate(indexUpdates.toArray(new Mutation[indexUpdates.size()]), HConstants.NO_NONCE, HConstants.NO_NONCE); } batchSize = 0; indexUpdates = new ArrayList<Mutation>(maxBatchSize); for (Mutation mutation : indexRowsToBeDeleted) { indexUpdates.add(mutation); batchSize ++; if (batchSize >= maxBatchSize) { ungroupedAggregateRegionObserver.checkForRegionClosing(); region.batchMutate(indexUpdates.toArray(new Mutation[indexUpdates.size()]), HConstants.NO_NONCE, HConstants.NO_NONCE); batchSize = 0; indexUpdates = new ArrayList<Mutation>(maxBatchSize); } } if (batchSize > 0) { ungroupedAggregateRegionObserver.checkForRegionClosing(); region.batchMutate(indexUpdates.toArray(new Mutation[indexUpdates.size()]), HConstants.NO_NONCE, HConstants.NO_NONCE); } if (verify) { verificationResult.setRebuiltIndexRowCount(verificationResult.getRebuiltIndexRowCount() + indexMutationMap.size()); } } catch (Throwable t) { ServerUtil.throwIOException(region.getRegionInfo().getRegionNameAsString(), t); } }

Target:
protected void repairIndexRows(Map<byte[], List<Mutation>> indexMutationMap, List<Mutation> indexRowsToBeDeleted, IndexToolVerificationResult verificationResult) throws IOException { updateIndexRows(indexMutationMap, indexRowsToBeDeleted, verificationResult); }
Source:
public String[] getFilePaths(RepoObject repoObject) throws RepoException { String[] paths = null; String s3Url = s3Client.getResourceUrl(repoObject.getBucketName(), repoObject.getChecksum()); if(s3Url != null){ paths = new String[]{s3Url}; } return paths; }

Target:
public String[] getFilePaths(RepoObject repoObject) throws RepoException { String s3Url = s3Client.getResourceUrl(repoObject.getBucketName(), repoObject.getChecksum()); if (s3Url == null) { throw new RepoException(RepoException.Type.ObjectFilePathMissing); } return new String[]{s3Url}; }
Source:
public void validatePatchRequest(JsonNode payload){ List<String> pathCheck = requestValidator.checkIfExistsOrEmpty(payload, FIELD_OPERATION, FIELD_OPERATION_PATH); if(!pathCheck.isEmpty()) throw new ValidationException(pathCheck); String path = payload.findValue(FIELD_OPERATION_PATH).asText().toLowerCase(); if(!VALID_PATHS.contains(path)) throw new ValidationException(Collections.singletonList(format("Operation [%s] not supported for path [%s]", FIELD_OPERATION, path))); switch (path) { case FIELD_NOTIFY_SETTINGS: validateNotifySettingsRequest(payload); break; case FIELD_EMAIL_COLLECTION_MODE: validateEmailCollectionMode(payload); break; case FIELD_ALLOW_WEB_PAYMENTS: validateAllowWebPayment(payload); break; case FIELD_COPORATE_CREDIT_CARD_SURCHARGE_AMOUNT: case FIELD_COPORATE_DEBIT_CARD_SURCHARGE_AMOUNT: case FIELD_COPORATE_PREPAID_CREDIT_CARD_SURCHARGE_AMOUNT: case FIELD_COPORATE_PREPAID_DEBIT_CARD_SURCHARGE_AMOUNT: validateCorporateSurchargePayLoad(payload); break; } }

Target:
public void validatePatchRequest(JsonNode payload){ List<String> pathCheck = requestValidator.checkIfExistsOrEmpty(payload, FIELD_OPERATION, FIELD_OPERATION_PATH); if(!pathCheck.isEmpty()) throw new ValidationException(pathCheck); String path = payload.findValue(FIELD_OPERATION_PATH).asText().toLowerCase(); if(!VALID_PATHS.contains(path)) throw new ValidationException(Collections.singletonList(format("Operation [%s] not supported for path [%s]", FIELD_OPERATION, path))); switch (path) { case FIELD_NOTIFY_SETTINGS: validateNotifySettingsRequest(payload); break; case FIELD_EMAIL_COLLECTION_MODE: validateEmailCollectionMode(payload); break; case FIELD_ALLOW_WEB_PAYMENTS: validateAllowWebPayment(payload); break; case FIELD_CORPORATE_CREDIT_CARD_SURCHARGE_AMOUNT: case FIELD_CORPORATE_DEBIT_CARD_SURCHARGE_AMOUNT: case FIELD_CORPORATE_PREPAID_CREDIT_CARD_SURCHARGE_AMOUNT: case FIELD_CORPORATE_PREPAID_DEBIT_CARD_SURCHARGE_AMOUNT: validateCorporateCardSurchargePayload(payload); break; } }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } return false; }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ID3v2TXXXFrameData other = (ID3v2TXXXFrameData) obj; if (!Objects.equals(this.description, other.description)) { return false; } if (!Objects.equals(this.value, other.value)) { return false; } return true; }
Source:
public SequencerReference get(long id) throws IOException { SequencerReference sr = (SequencerReference) currentSession().get(SequencerReferenceImpl.class, id); SequencerReference preUpgradeSR = getByUpgradedReference(id); if (preUpgradeSR != null) { sr.setPreUpgradeSequencerReference(preUpgradeSR); } return sr; }

Target:
public SequencerReference get(long id) throws IOException { return (SequencerReference) currentSession().get(SequencerReferenceImpl.class, id); }
Source:
public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (x != pair.x) return false; return y == pair.y; }

Target:
public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return x == pair.x && y == pair.y; }
Source:
public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException { checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD); FilePath ws = getSomeWorkspace(); if (ws!=null) { ws.deleteRecursive(); for (WorkspaceListener wl : WorkspaceListener.all()) { wl.afterDelete(this); } return new HttpRedirect("."); } else { return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly"); } }

Target:
public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException { checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD); R b = getSomeBuildWithWorkspace(); FilePath ws = b!=null ? b.getWorkspace() : null; if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) { ws.deleteRecursive(); for (WorkspaceListener wl : WorkspaceListener.all()) { wl.afterDelete(this); } return new HttpRedirect("."); } else { return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly"); } }
Source:
public Action<?, ?> finishedAction() { return new AbstractEnvStackConfigUpdatesAction<>(ResourceCrnPayload.class) { @Override protected void doExecute(CommonContext context, ResourceCrnPayload payload, Map<Object, Object> variables) { EnvironmentDto environmentDto = environmentStatusUpdateService .updateEnvironmentStatusAndNotify(context, payload, getCurrentStatus(payload.getResourceId()), ResourceEvent.ENVIRONMENT_STACK_CONFIGS_UPDATE_FINISHED, EnvStackConfigUpdatesState.STACK_CONFIG_UPDATES_FINISHED_STATE); metricService.incrementMetricCounter(MetricType.ENV_STACK_CONFIG_UPDATE_FINISHED, environmentDto); LOGGER.info("Flow entered into ENV_STOP_FINISHED_STATE"); sendEvent(context, FINALIZE_ENV_STACK_CONIFG_UPDATES_EVENT.event(), payload); } }; }

Target:
public Action<?, ?> finishedAction() { return new AbstractEnvStackConfigUpdatesAction<>(ResourceCrnPayload.class) { @Override protected void doExecute(CommonContext context, ResourceCrnPayload payload, Map<Object, Object> variables) { EnvironmentDto environmentDto = environmentStatusUpdateService .updateEnvironmentStatusAndNotify(context, payload, getCurrentStatus(payload.getResourceId()), ResourceEvent.ENVIRONMENT_STACK_CONFIGS_UPDATE_FINISHED, EnvStackConfigUpdatesState.STACK_CONFIG_UPDATES_FINISHED_STATE); metricService.incrementMetricCounter(MetricType.ENV_STACK_CONFIG_UPDATE_FINISHED, environmentDto); LOGGER.info("Flow entered into STACK_CONFIG_UPDATES_FINISHED_STATE"); sendEvent(context, FINALIZE_ENV_STACK_CONIFG_UPDATES_EVENT.event(), payload); } }; }
Source:
public void deletePools(List<Pool> pools) { if (log.isDebugEnabled()) { log.debug("Delete pools: {}", getPoolIds(pools)); } if (pools.isEmpty()) { return; } List<Entitlement> entitlementsToRevoke = new ArrayList<Entitlement>(); for (Pool p : pools) { if (log.isDebugEnabled()) { log.debug("Deletion of pool will cause revocation of the " + "following entitlements: {}.", p.getId(), getEntIds(p.getEntitlements())); } entitlementsToRevoke.addAll(p.getEntitlements()); } if (!pools.isEmpty()) { revokeEntitlements(entitlementsToRevoke); log.debug("Batch deleting pools after successfull revocation"); poolCurator.batchDelete(pools); } for (Pool pool : pools) { Event event = eventFactory.poolDeleted(pool); sink.queueEvent(event); } }

Target:
public void deletePools(List<Pool> pools) { if (log.isDebugEnabled()) { log.debug("Delete pools: {}", getPoolIds(pools)); } if (pools.isEmpty()) { return; } List<Entitlement> entitlementsToRevoke = new ArrayList<Entitlement>(); for (Pool p : pools) { if (log.isDebugEnabled()) { log.debug("Deletion of pool will cause revocation of the " + "following entitlements: {}.", p.getId(), getEntIds(p.getEntitlements())); } entitlementsToRevoke.addAll(p.getEntitlements()); } if (!pools.isEmpty()) { revokeEntitlements(entitlementsToRevoke); log.debug("Batch deleting pools after successful revocation"); poolCurator.batchDelete(pools); } for (Pool pool : pools) { Event event = eventFactory.poolDeleted(pool); sink.queueEvent(event); } }
Source:
public Response getServer(@PathParam("id") String queryId, @Context final HttpServletRequest req) { if (authConfig.isEnabled()) { final AuthorizationInfo authorizationInfo = (AuthorizationInfo) req.getAttribute(AuthConfig.DRUID_AUTH_TOKEN); Preconditions.checkNotNull( authorizationInfo, "Security is enabled but no authorization info found in the request" ); if (queryManager.getQueryDatasources(queryId) == null) { log.warn("QueryId [%s] not registered with QueryManager, cannot cancel", queryId); } else if (authorizationInfo != null) { for (String dataSource : queryManager.getQueryDatasources(queryId)) { Access authResult = authorizationInfo.isAuthorized( new Resource(dataSource, ResourceType.DATASOURCE), Action.WRITE ); if (!authResult.isAllowed()) { return Response.status(Response.Status.FORBIDDEN).header("Access-Check-Result", authResult).build(); } } } else { throw new ISE("WTF?! Security is enabled but no authorization info found in the request"); } } queryManager.cancelQuery(queryId); return Response.status(Response.Status.ACCEPTED).build(); }

Target:
public Response getServer(@PathParam("id") String queryId, @Context final HttpServletRequest req) { if (log.isDebugEnabled()) { log.debug("Received cancel request for query [%s]", queryId); } if (authConfig.isEnabled()) { final AuthorizationInfo authorizationInfo = (AuthorizationInfo) req.getAttribute(AuthConfig.DRUID_AUTH_TOKEN); Preconditions.checkNotNull( authorizationInfo, "Security is enabled but no authorization info found in the request" ); Set<String> datasources = queryManager.getQueryDatasources(queryId); if (datasources == null) { log.warn("QueryId [%s] not registered with QueryManager, cannot cancel", queryId); } else { for (String dataSource : datasources) { Access authResult = authorizationInfo.isAuthorized( new Resource(dataSource, ResourceType.DATASOURCE), Action.WRITE ); if (!authResult.isAllowed()) { return Response.status(Response.Status.FORBIDDEN).header("Access-Check-Result", authResult).build(); } } } } queryManager.cancelQuery(queryId); return Response.status(Response.Status.ACCEPTED).build(); }
Source:
protected static TenantStatus getTenantStatus(String tenantDomain) { boolean isTenantContextLoaded = false; Map<String, ConfigurationContext> tenantConfigContextsServer = getTenantConfigContexts(); if (tenantConfigContextsServer != null) { isTenantContextLoaded = tenantConfigContextsServer.containsKey(tenantDomain); log.info("Tenant " + tenantDomain + " loaded :" + isTenantContextLoaded); } return new TenantStatus(isTenantContextLoaded); }

Target:
protected static TenantStatus getTenantStatus(String tenantDomain) { boolean isTenantContextLoaded = false; Map<String, ConfigurationContext> tenantConfigServerContexts = getTenantConfigServerContexts(); if (tenantConfigServerContexts != null) { isTenantContextLoaded = tenantConfigServerContexts.containsKey(tenantDomain); log.info("Tenant " + tenantDomain + " loaded :" + isTenantContextLoaded); } return new TenantStatus(isTenantContextLoaded); }
Source:
public void testLikeMatchCase_v1_0() throws Exception { String filter = "<wfs:GetFeature service=\"WFS\" version=\"1.0.0\" " + "outputFormat=\"GML2\" " + "xmlns:topp=\"<LINK_4>\" " + "xmlns:wfs=\"<LINK_5>\" " + "xmlns:ogc=\"<LINK_1>\" " + "xmlns:xsi=\"<LINK_0>\" " + "xsi:schemaLocation=\"<LINK_5> <LINK_2>\">" + "<wfs:Query typeName=\"cite:Buildings\">" + "<Filter xmlns=\"<LINK_1>\" xmlns:gml=\"<LINK_3>\">" + "<PropertyIsLike wildCard=\"*\" singleChar=\".\" escapeChar=\"\\\" matchCase=\"false\">" + "<PropertyName>ADDRESS</PropertyName>" + "<Literal>* MAIN STREET</Literal>" + "</PropertyIsLike>" + "</Filter>" + "</wfs:Query>" + "</wfs:GetFeature>"; StringReader reader = new StringReader( filter ); InputSource requestSource = new InputSource(reader); MyHandler contentHandler = new MyHandler(); FilterFilter filterParser = new FilterFilter(contentHandler, null); GMLFilterGeometry geometryFilter = new GMLFilterGeometry(filterParser); GMLFilterDocument documentFilter = new GMLFilterDocument(geometryFilter); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); ParserAdapter adapter = new ParserAdapter(parser.getParser()); adapter.setContentHandler(documentFilter); adapter.parse(requestSource); assertEquals(contentHandler.filters.size(),1); }

Target:
public void testLikeMatchCase_v1_0() throws Exception { testLikeMatchCase_v1_0(true); testLikeMatchCase_v1_0(false); }
Source:
public synchronized void shutdownGracefully() { final ApnsConnection<T> apnsConnection = this; if (this.hasCompletedHandshake() && this.connectFuture.channel().isActive()) { this.connectFuture.channel().eventLoop().execute(new Runnable() { public void run() { if (apnsConnection.shutdownNotification == null) { log.debug("{} sending known-bad notification to shut down.", apnsConnection.name); apnsConnection.shutdownNotification = new SendableApnsPushNotification<KnownBadPushNotification>( new KnownBadPushNotification(), apnsConnection.sequenceNumber++); apnsConnection.pendingWriteCount += 1; apnsConnection.connectFuture.channel().writeAndFlush(apnsConnection.shutdownNotification).addListener(new GenericFutureListener<ChannelFuture>() { public void operationComplete(final ChannelFuture future) { if (future.isSuccess()) { log.trace("{} successfully wrote known-bad notification {}", apnsConnection.name, apnsConnection.shutdownNotification.getSequenceNumber()); } else { log.trace("{} failed to write known-bad notification {}", apnsConnection.name, apnsConnection.shutdownNotification, future.cause()); apnsConnection.shutdownNotification = null; apnsConnection.shutdownGracefully(); } apnsConnection.pendingWriteCount -= 1; assert apnsConnection.pendingWriteCount >= 0; if (apnsConnection.pendingWriteCount == 0) { synchronized (apnsConnection.pendingWriteMonitor) { apnsConnection.pendingWriteMonitor.notifyAll(); } } } }); } } }); } else { this.shutdownImmediately(); } }

Target:
public synchronized void shutdownGracefully() { final ApnsConnection<T> apnsConnection = this; if (this.handshakeCompleted && this.connectFuture.channel().isActive()) { this.connectFuture.channel().eventLoop().execute(new Runnable() { public void run() { if (apnsConnection.shutdownNotification == null) { log.debug("{} sending known-bad notification to shut down.", apnsConnection.name); apnsConnection.shutdownNotification = new SendableApnsPushNotification<KnownBadPushNotification>( new KnownBadPushNotification(), apnsConnection.sequenceNumber++); apnsConnection.pendingWriteCount += 1; apnsConnection.connectFuture.channel().writeAndFlush(apnsConnection.shutdownNotification).addListener(new GenericFutureListener<ChannelFuture>() { public void operationComplete(final ChannelFuture future) { if (future.isSuccess()) { log.trace("{} successfully wrote known-bad notification {}", apnsConnection.name, apnsConnection.shutdownNotification.getSequenceNumber()); } else { log.trace("{} failed to write known-bad notification {}", apnsConnection.name, apnsConnection.shutdownNotification, future.cause()); apnsConnection.shutdownNotification = null; apnsConnection.shutdownGracefully(); } apnsConnection.pendingWriteCount -= 1; assert apnsConnection.pendingWriteCount >= 0; if (apnsConnection.pendingWriteCount == 0) { synchronized (apnsConnection.pendingWriteMonitor) { apnsConnection.pendingWriteMonitor.notifyAll(); } } } }); } } }); } else { this.shutdownImmediately(); } }