auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean match(String cluster, String service) { if (_cluster == null && _service == null) { return true; } else if (_cluster == null) { return Objects.equals(_service, service); } else if (_service == null) { return Objects.equals(_cluster, cluster); } else { return Objects.equals(_cluster, cluster) && Objects.equals(_service, service); } }

Target:
public boolean match(String cluster, String service) { if (this == WILDCARD_KEY) { return true; } else if (_cluster == null) { return Objects.equals(_service, service); } else if (_service == null) { return Objects.equals(_cluster, cluster); } else { return Objects.equals(_cluster, cluster) && Objects.equals(_service, service); } }
Source:
public ResourceManager withDefaultSubscription() { if (profile.subscriptionId() == null) { List<Subscription> subscriptions = new ArrayList<>(); this.subscriptions().list().forEach(subscription -> { subscriptions.add(subscription); }); if (subscriptions.size() == 0) { throw logger.logExceptionAsError( new RuntimeException("Please create a subscription before you start resource management. " + "To learn more, see: <LINK_0>")); } else if (subscriptions.size() > 1) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("More than one subscription found in your tenant. " + "Please specify which one below is desired for resource management."); subscriptions.forEach(subscription -> { stringBuilder.append("\n" + subscription.displayName() + " : " + subscription.subscriptionId()); }); throw logger.logExceptionAsError(new RuntimeException(stringBuilder.toString())); } else { profile.withSubscriptionId(subscriptions.get(0).subscriptionId()); } } return new ResourceManager(httpPipeline, profile, sdkContext); }

Target:
public ResourceManager withDefaultSubscription() { if (profile.subscriptionId() == null) { profile.withSubscriptionId(Utils.defaultSubscription(this.subscriptions().list())); } return new ResourceManager(httpPipeline, profile, sdkContext); }
Source:
private static RefList<Ref> applyUpdates(RevWalk walk, RefList<Ref> refs, List<ReceiveCommand> commands) throws IOException { Collections.sort(commands, new Comparator<ReceiveCommand>() { @Override public int compare(ReceiveCommand a, ReceiveCommand b) { return a.getRefName().compareTo(b.getRefName()); } }); int delta = 0; for (ReceiveCommand c : commands) { switch (c.getType()) { case DELETE: delta--; break; case CREATE: delta++; break; default: } } RefList.Builder<Ref> b = new RefList.Builder<>(refs.size() + delta); int refIdx = 0; int cmdIdx = 0; while (refIdx < refs.size() || cmdIdx < commands.size()) { Ref ref = (refIdx < refs.size()) ? refs.get(refIdx) : null; ReceiveCommand cmd = (cmdIdx < commands.size()) ? commands.get(cmdIdx) : null; int cmp = 0; if (ref != null && cmd != null) { cmp = ref.getName().compareTo(cmd.getRefName()); } else if (ref == null) { cmp = 1; } else if (cmd == null) { cmp = -1; } if (cmp < 0) { b.add(ref); refIdx++; } else if (cmp > 0) { if (cmd.getType() != ReceiveCommand.Type.CREATE) { lockFailure(cmd, commands); return null; } b.add(peeledRef(walk, cmd)); cmdIdx++; } else { if (!cmd.getOldId().equals(ref.getObjectId())) { lockFailure(cmd, commands); return null; } if (cmd.getType() != ReceiveCommand.Type.DELETE) { b.add(peeledRef(walk, cmd)); } cmdIdx++; refIdx++; } } return b.toRefList(); }

Target:
private static RefList<Ref> applyUpdates(RevWalk walk, RefList<Ref> refs, List<ReceiveCommand> commands) throws IOException { Collections.sort(commands, new Comparator<ReceiveCommand>() { @Override public int compare(ReceiveCommand a, ReceiveCommand b) { return a.getRefName().compareTo(b.getRefName()); } }); int delta = 0; for (ReceiveCommand c : commands) { switch (c.getType()) { case DELETE: delta--; break; case CREATE: delta++; break; default: } } RefList.Builder<Ref> b = new RefList.Builder<>(refs.size() + delta); int refIdx = 0; int cmdIdx = 0; while (refIdx < refs.size() || cmdIdx < commands.size()) { Ref ref = (refIdx < refs.size()) ? refs.get(refIdx) : null; ReceiveCommand cmd = (cmdIdx < commands.size()) ? commands.get(cmdIdx) : null; int cmp = 0; if (ref != null && cmd != null) { cmp = ref.getName().compareTo(cmd.getRefName()); } else if (ref == null) { cmp = 1; } else if (cmd == null) { cmp = -1; } if (cmp < 0) { b.add(ref); refIdx++; } else if (cmp > 0) { assert cmd != null; if (cmd.getType() != ReceiveCommand.Type.CREATE) { lockFailure(cmd, commands); return null; } b.add(peeledRef(walk, cmd)); cmdIdx++; } else { assert cmd != null; assert ref != null; if (!cmd.getOldId().equals(ref.getObjectId())) { lockFailure(cmd, commands); return null; } if (cmd.getType() != ReceiveCommand.Type.DELETE) { b.add(peeledRef(walk, cmd)); } cmdIdx++; refIdx++; } } return b.toRefList(); }
Source:
public double rate( PricingEnvironment env, IborAveragedRateObservation observation, LocalDate startDate, LocalDate endDate) { double totalWeight = observation.getFixings().stream() .mapToDouble(IborAveragedFixing::getWeight) .sum(); double weightedRate = observation.getFixings().stream() .mapToDouble(fixing -> weightedRate(env, observation.getIndex(), fixing)) .sum(); return weightedRate / totalWeight; }

Target:
public double rate( PricingEnvironment env, IborAveragedRateObservation observation, LocalDate startDate, LocalDate endDate) { double weightedRate = observation.getFixings().stream() .mapToDouble(fixing -> weightedRate(env, observation.getIndex(), fixing)) .sum(); return weightedRate / observation.getTotalWeight(); }
Source:
public void testGerritEventManualEvent() { AbstractProject project = PowerMockito.mock(AbstractProject.class); when(project.getFullName()).thenReturn("MockedProject"); when(project.isBuildable()).thenReturn(true); mockConfig(project); PowerMockito.mockStatic(ToGerritRunListener.class); ToGerritRunListener listener = PowerMockito.mock(ToGerritRunListener.class); PowerMockito.when(ToGerritRunListener.getInstance()).thenReturn(listener); GerritProject gP = mock(GerritProject.class); doReturn(true).when(gP).isInteresting(any(String.class), any(String.class), any(String.class)); when(gP.getFilePaths()).thenReturn(null); GerritTrigger trigger = Setup.createDefaultTrigger(project, new Setup.ScheduleProxy() { @Override public boolean schedule(Job theJob, int quitePeriod, GerritCause cause, BadgeAction badgeAction, ParametersAction parameters) { Assert.assertEquals(0, quitePeriod); Assert.assertTrue(cause instanceof GerritUserCause); Assert.assertTrue(badgeAction instanceof BadgeAction); Assert.assertTrue(parameters instanceof ParametersAction); return false; } }); Setup.setTrigger(trigger, project); trigger.setGerritProjects(Collections.nCopies(1, gP)); trigger.setEscapeQuotes(false); trigger.setSilentMode(false); Whitebox.setInternalState(trigger, "job", project); ManualPatchsetCreated event = Setup.createManualPatchsetCreated(); trigger.createListener().gerritEvent(event); verify(listener).onTriggered(same(project), same(event)); }

Target:
public void testGerritEventManualEvent() { AbstractProject project = PowerMockito.mock(AbstractProject.class); when(project.getFullName()).thenReturn("MockedProject"); when(project.isBuildable()).thenReturn(true); mockConfig(project); PowerMockito.mockStatic(ToGerritRunListener.class); ToGerritRunListener listener = PowerMockito.mock(ToGerritRunListener.class); PowerMockito.when(ToGerritRunListener.getInstance()).thenReturn(listener); GerritProject gP = mock(GerritProject.class); doReturn(true).when(gP).isInteresting(any(String.class), any(String.class), any(String.class)); when(gP.getFilePaths()).thenReturn(null); Setup.ScheduleProxy scheduleTestProxy = new Setup.ScheduleProxy() { @Override public boolean schedule(Job theJob, int quitePeriod, GerritCause cause, BadgeAction badgeAction, ParametersAction parameters) { Assert.assertEquals(0, quitePeriod); Assert.assertTrue(cause instanceof GerritUserCause); Assert.assertTrue(badgeAction instanceof BadgeAction); Assert.assertTrue(parameters instanceof ParametersAction); return false; } }; GerritTrigger trigger = Setup.createDefaultTrigger(project, scheduleTestProxy); Setup.setTrigger(trigger, project); trigger.setGerritProjects(Collections.nCopies(1, gP)); trigger.setEscapeQuotes(false); trigger.setSilentMode(false); Whitebox.setInternalState(trigger, "job", project); ManualPatchsetCreated event = Setup.createManualPatchsetCreated(); trigger.createListener().gerritEvent(event); verify(listener).onTriggered(same(project), same(event)); assertTrue(scheduleTestProxy.wasScheduled()); }
Source:
protected boolean failPassthroughVnicHotPlug() { if (VmInterfaceType.pciPassthrough.equals(VmInterfaceType.forValue(getParameters().getNic().getType()))) { addCanDoActionMessage(EngineMessage.HOT_PLUG_UNPLUG_PASSTHROUGH_VNIC_NOT_SUPPORTED); return true; } return false; }

Target:
protected boolean failPassthroughVnicHotPlug() { if (VmInterfaceType.pciPassthrough == VmInterfaceType.forValue(getParameters().getNic().getType())) { addCanDoActionMessage(EngineMessage.HOT_PLUG_UNPLUG_PASSTHROUGH_VNIC_NOT_SUPPORTED); return true; } return false; }
Source:
public Collection<TopologyComponentDefinition> listTopologyComponentsForTypeWithFilter(TopologyComponentDefinition.TopologyComponentType componentType, List<QueryParam> params) { List<TopologyComponentDefinition> topologyComponentDefinitions = new ArrayList<TopologyComponentDefinition>(); String ns = TopologyComponentDefinition.NAME_SPACE; Collection<TopologyComponentDefinition> filtered = dao.<TopologyComponentDefinition>find(ns, params); for (TopologyComponentDefinition tc : filtered) { if (tc.getType().equals(componentType)) { topologyComponentDefinitions.add(tc); } } return topologyComponentDefinitions; }

Target:
public Collection<TopologyComponentDefinition> listTopologyComponentsForTypeWithFilter(TopologyComponentDefinition.TopologyComponentType componentType, List<QueryParam> params) { List<TopologyComponentDefinition> topologyComponentDefinitions = new ArrayList<>(); String ns = TopologyComponentDefinition.NAME_SPACE; Collection<TopologyComponentDefinition> filtered = dao.find(ns, params); for (TopologyComponentDefinition tc : filtered) { if (tc.getType().equals(componentType)) { topologyComponentDefinitions.add(tc); } } return topologyComponentDefinitions; }
Source:
public UniqueId(final HBaseClient client, final byte[] table, final String kind, final int width) { this.client = client; this.table = table; if (kind.isEmpty()) { throw new IllegalArgumentException("Empty string as 'kind' argument!"); } this.kind = toBytes(kind); if (width < 1 || width > 8) { throw new IllegalArgumentException("Invalid width: " + width); } this.idWidth = (short) width; this.idLimit = (long) Math.pow(2, idWidth * Byte.SIZE) - 1; }

Target:
public UniqueId(final HBaseClient client, final byte[] table, final String kind, final int width) { this.client = client; this.table = table; if (kind.isEmpty()) { throw new IllegalArgumentException("Empty string as 'kind' argument!"); } this.kind = toBytes(kind); if (width < 1 || width > 8) { throw new IllegalArgumentException("Invalid width: " + width); } this.idWidth = (short) width; }
Source:
private static ContinuousStream<Map<String, Object>> cepCCTranslator( final ContinuousStream<Map<String, Object>> input, final ComparisonCondition condition) { String field = condition.getFieldName(); Object value = condition.getComparisonValue(); switch(condition.getConditionType()){ case LT: return input.filter(s -> cepCompare(s.get(field), value) < 0); case GT: return input.filter(s -> cepCompare(s.get(field), value) > 0); case EQ: return input.filter(s -> s.get(field).equals(value)); default: throw new IllegalStateException("Wrong comparison condition type!"); } }

Target:
private static ContinuousStream<Map<String, Object>> cepCCTranslator( final ContinuousStream<Map<String, Object>> input, final ComparisonCondition condition) { final String field = condition.getFieldName(); final Object value = condition.getComparisonValue(); final ConditionType conditionType = condition.getConditionType(); switch (conditionType) { case GT: return input.filter(new CepGTPredicate(field, value)); case LT: return input.filter(new CepLTPredicate(field, value)); case EQ: return input.filter(new CepEQPredicate(field, value)); case NEQ: return input.filter(new CepNEQPredicate(field, value)); default: throw new IllegalStateException("Wrong comparison condition type!"); } }
Source:
protected void logRequest() { BoxLogUtils.i(BoxConstants.TAG, String.format(Locale.ENGLISH, "Request (%s): %s", mRequestMethod, mRequestUrlString)); BoxLogUtils.i(BoxConstants.TAG, "Request Header", mHeaderMap); switch (mContentType) { case JSON: if (!SdkUtils.isBlank(mStringBody)) { BoxLogUtils.i(BoxConstants.TAG, String.format(Locale.ENGLISH, "Request JSON: %s", mStringBody)); } break; case URL_ENCODED: HashMap<String, String> stringMap = new HashMap<String, String>(); for (Map.Entry<String,Object> entry : mBodyMap.entrySet()) { stringMap.put(entry.getKey(), (String)entry.getValue()); } BoxLogUtils.i(BoxConstants.TAG, "Request Form Data", stringMap); break; case JSON_PATCH: if (!SdkUtils.isBlank(mStringBody)) { BoxLogUtils.i(BoxConstants.TAG, String.format(Locale.ENGLISH, "Request JSON: %s", mStringBody)); } break; default: break; } }

Target:
protected void logRequest() { BoxLogUtils.i(BoxConstants.TAG, String.format(Locale.ENGLISH, "Request (%s): %s", mRequestMethod, mRequestUrlString)); BoxLogUtils.i(BoxConstants.TAG, "Request Header", mHeaderMap); switch (mContentType) { case JSON: case JSON_PATCH: if (!SdkUtils.isBlank(mStringBody)) { BoxLogUtils.i(BoxConstants.TAG, String.format(Locale.ENGLISH, "Request JSON: %s", mStringBody)); } break; case URL_ENCODED: HashMap<String, String> stringMap = new HashMap<String, String>(); for (Map.Entry<String,Object> entry : mBodyMap.entrySet()) { stringMap.put(entry.getKey(), (String)entry.getValue()); } BoxLogUtils.i(BoxConstants.TAG, "Request Form Data", stringMap); break; default: break; } }
Source:
public ImportVmParameters(VM vm, Guid sourceStorageDomainId, Guid destStorageDomainId, Guid storagePoolId, Guid vdsGroupId) { super(vm.getId(), destStorageDomainId); this.setSourceDomainId(sourceStorageDomainId); this.setDestDomainId(destStorageDomainId); setVm(vm); setStorageDomainId(destStorageDomainId); setStoragePoolId(storagePoolId); setVdsGroupId(vdsGroupId); }

Target:
public ImportVmParameters(VM vm, Guid sourceStorageDomainId, Guid destStorageDomainId, Guid storagePoolId, Guid vdsGroupId) { super(vm.getId(), destStorageDomainId); sourceDomainId = sourceStorageDomainId; destDomainId = destStorageDomainId; setVm(vm); setStorageDomainId(destStorageDomainId); setStoragePoolId(storagePoolId); setVdsGroupId(vdsGroupId); }
Source:
LockDescriptorAwareRepresenter() { this.representers.put(LockDescriptor.class, data -> representScalar(Tag.STR, data.toString())); }

Target:
LockDescriptorAwareRepresenter() { super(); this.representers.put(LockDescriptor.class, data -> representScalar(Tag.STR, data.toString())); }
Source:
public KoreKDebug(K initialK, Rewriter rewriter) { this.stateSet = new HashSet<>(); this.checkpointInterval = DEFAULT_CHECKPOINT_SIZE; this.rewriter = rewriter; KDebugState initialState = new KDebugState(initialK); initialState.addCheckpoint(new Checkpoint(initialK, DEFAULT_ID), DEFAULT_ID); stateSet.add(initialState); activeState = initialState; }

Target:
public KoreKDebug(K initialK, Rewriter rewriter) { this.stateList = new ArrayList<>(); this.checkpointInterval = DEFAULT_CHECKPOINT_SIZE; this.rewriter = rewriter; NavigableMap<Integer, RewriterCheckpoint> checkpointMap = new TreeMap<>(); checkpointMap.put(DEFAULT_ID, new RewriterCheckpoint(initialK)); DebuggerState initialState = new DebuggerState(initialK, DEFAULT_ID, checkpointMap); stateList.add(initialState); activeState = initialState; }
Source:
public void should_add_error_to_context_but_not_fail_analysis_with_technical_error() { JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); InputFile file = inputFile("file.js"); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor) check), ImmutableList.of(file), executor, progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); assertThat(logTester.logs()).contains("Unable to analyse file: " + file.toString()); }

Target:
public void should_add_error_to_context_but_not_fail_analysis_with_technical_error() { JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); InputFile file = inputFile("file.js"); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor) check), ImmutableList.of(file), executor, progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); assertThat(logTester.logs()).contains("Unable to analyse file: " + file.uri()); }
Source:
private Map<Class<? extends Service>, Object> createProvidedServices(SearchConfiguration searchConfiguration) { Map<Class<? extends Service>, Object> tmpServices = new HashMap<Class<? extends Service>, Object>(); tmpServices.putAll( searchConfiguration.getProvidedServices() ); if ( tmpServices.containsKey( ClassLoaderService.class ) ) { throw log.classLoaderServiceContainedInProvidedServicesException(); } else { tmpServices.put( ClassLoaderService.class, searchConfiguration.getClassLoaderService() ); } return Collections.unmodifiableMap( tmpServices ); }

Target:
private Map<Class<? extends Service>, Object> createProvidedServices(SearchConfiguration searchConfiguration) { Map<Class<? extends Service>, Object> tmpServices = new HashMap<Class<? extends Service>, Object>(); for ( Map.Entry<Class<? extends Service>, Object> entry : searchConfiguration.getProvidedServices() .entrySet() ) { Object service = entry.getValue(); if ( service instanceof Startable ) { throw log.providedServicesCannotImplementStartableOrStoppable( service.getClass().getName(), Startable.class.getName() ); } else if ( service instanceof Stoppable ) { throw log.providedServicesCannotImplementStartableOrStoppable( service.getClass().getName(), Stoppable.class.getName() ); } else { tmpServices.put( entry.getKey(), entry.getValue() ); } } if ( tmpServices.containsKey( ClassLoaderService.class ) ) { throw log.classLoaderServiceContainedInProvidedServicesException(); } else { tmpServices.put( ClassLoaderService.class, searchConfiguration.getClassLoaderService() ); } return Collections.unmodifiableMap( tmpServices ); }
Source:
public void createSchemaSpecificSchedulers() throws BeansException { logger.info("In postProcessBeanFactory"); Set<String> schemas = studyDao.findAll().stream() .map(study -> study.getSchemaName()) .collect(Collectors.toSet()); for (String schema : schemas) { CoreResources.setRequestSchema(schema); if (ocQrtzTriggersDAO.findAll().size() != 0) { CoreResources.setRequestSchema("public"); logger.info("Found triggers in " + schema); schedulerUtilService.createSchedulerFactoryBean(applicationContext, schema); } } }

Target:
public void createSchemaSpecificSchedulers() throws BeansException { logger.info("In postProcessBeanFactory"); Set<String> schemas = studyDao.findAll().stream() .map(study -> study.getSchemaName()) .collect(Collectors.toSet()); for (String schema : schemas) { CoreResources.setRequestSchema(schema); if (ocQrtzTriggersDAO.findAll().size() != 0) { logger.info("Found triggers in " + schema); schedulerUtilService.createSchedulerFactoryBean(applicationContext, schema); } } }
Source:
public static synchronized CamelReactiveStreams get(CamelContext context) { if (!instances.containsKey(context)) { CamelReactiveStreamsService service = resolveReactiveStreamsService(context); try { context.addService(service, true, true); } catch (Exception ex) { throw new IllegalStateException("Cannot add the CamelReactiveStreamsService to the Camel context", ex); } instances.put(context, new CamelReactiveStreams(service)); } return instances.get(context); }

Target:
public static CamelReactiveStreamsService get(CamelContext context) { return get(context, null); }
Source:
public <T> void put(VdcParameter param, T value) { VdcParameterValue.raiseExceptionIfInvalidObjectType(param, value); paramsMap.put(param.getGuid(), new VdcParameterValue<T>(param, value)); }

Target:
public <T> void put(VdcParameter param, T value) { Pair.raiseExceptionIfInvalidObjectType(param, value); paramsMap.put(param, value); }
Source:
public void run() { B batch = null; do { try { batch = changeSource.firstBatch(); } catch (RetryableException e) { log.warn("Retryable error fetching first batch. Retrying.", e); } } while (batch == null); log.debug("{} changes in batch", batch.changes().size()); Instant oldDate = null; while (!currentThread().isInterrupted()) { try { handleChanges(batch.changes()); Instant leftOffDate = batch.leftOffDate(); if (leftOffDate != null) { leftOffDate = leftOffDate.minusSeconds(1); if (oldDate == null || !oldDate.equals(leftOffDate)) { syncDate(leftOffDate); oldDate = leftOffDate; } } batchAdvanced.mark(batch.advanced()); log.info("Polled up to at updates per second and per second", batch.leftOffHuman(), meterReport(updatesMeter), meterReport(batchAdvanced), batch.advancedUnits()); if (batch.last()) { return; } streamDumper.rotate(); batch = nextBatch(batch); } catch (InterruptedException e) { currentThread().interrupt(); } catch (ExecutionException e) { log.error("Syncing encountered a fatal exception", e); break; } } }

Target:
public void run() { B batch = null; do { try { batch = changeSource.firstBatch(); } catch (RetryableException e) { log.warn("Retryable error fetching first batch. Retrying.", e); } } while (batch == null); log.debug("{} changes in batch", batch.changes().size()); Instant oldDate = null; while (!currentThread().isInterrupted()) { try { handleChanges(batch.changes()); Instant leftOffDate = batch.leftOffDate(); if (leftOffDate != null) { leftOffDate = leftOffDate.minusSeconds(1); if (oldDate == null || !oldDate.equals(leftOffDate)) { syncDate(leftOffDate); oldDate = leftOffDate; } } batchAdvanced.mark(batch.advanced()); log.info("Polled up to at updates per second and per second", batch.leftOffHuman(), meterReport(updatesMeter), meterReport(batchAdvanced), batch.advancedUnits()); if (batch.last()) { return; } wikibase.batchDone(); batch = nextBatch(batch); } catch (InterruptedException e) { currentThread().interrupt(); } catch (ExecutionException e) { log.error("Syncing encountered a fatal exception", e); break; } } }
Source:
public void requestNetworkScanLocationOffHelper(boolean includeBandsAndChannels) { if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { Log.e(TAG, "No cellular support, the test will be skipped."); return; } if (!mTelephonyManager.hasCarrierPrivileges()) { fail("This test requires a SIM card with carrier privilege rule on it."); } mNetworkScanRequest = buildNetworkScanRequest(includeBandsAndChannels); for (int i = 0; i < mNetworkScanRequest.getSpecifiers().length; i++) { int[] bands = includeBandsAndChannels ? new int[]{1} : null; mNetworkScanRequest.getSpecifiers()[i] = new RadioAccessSpecifier( mNetworkScanRequest.getSpecifiers()[i].getRadioAccessNetwork(), bands, null); } boolean isLocationSwitchOn = cacheAndTurnOffLocationSwitch(); try { mNetworkScanCallback = new NetworkScanCallbackImpl(); Message startNetworkScan = mHandler.obtainMessage(EVENT_NETWORK_SCAN_START); setReady(false); startNetworkScan.sendToTarget(); waitUntilReady(); if (includeBandsAndChannels) { assertEquals(EVENT_SCAN_DENIED, mNetworkScanStatus); return; } Log.d(TAG, "mNetworkScanStatus: " + mNetworkScanStatus); assertTrue("The final scan status is not ScanCompleted or ScanError with an error " + "code ERROR_MODEM_UNAVAILABLE or ERROR_UNSUPPORTED", isScanStatusValid()); } finally { setLocationSwitch(isLocationSwitchOn); } }

Target:
public void requestNetworkScanLocationOffHelper(boolean includeBandsAndChannels) { if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { Log.e(TAG, "No cellular support, the test will be skipped."); return; } if (!mTelephonyManager.hasCarrierPrivileges()) { fail("This test requires a SIM card with carrier privilege rule on it."); } mNetworkScanRequest = buildNetworkScanRequest(includeBandsAndChannels); boolean isLocationSwitchOn = cacheAndTurnOffLocationSwitch(); try { mNetworkScanCallback = new NetworkScanCallbackImpl(); Message startNetworkScan = mHandler.obtainMessage(EVENT_NETWORK_SCAN_START); setReady(false); startNetworkScan.sendToTarget(); waitUntilReady(); if (includeBandsAndChannels) { assertEquals(EVENT_SCAN_DENIED, mNetworkScanStatus); return; } Log.d(TAG, "mNetworkScanStatus: " + mNetworkScanStatus); assertTrue("The final scan status is not ScanCompleted or ScanError with an error " + "code ERROR_MODEM_UNAVAILABLE or ERROR_UNSUPPORTED", isScanStatusValid()); } finally { setLocationSwitch(isLocationSwitchOn); } }
Source:
private void generateGeneralInsights(final Long accountId, final Long deviceId) { final Set<InsightCard.Category> recentCategories = this.getRecentInsightsCategories(accountId); Integer dayOfWeek = Integer.parseInt(DateTime.now().dayOfWeek().getAsString()); LOGGER.debug("The day of week is {}", dayOfWeek); InsightCard.Category categoryToGenerate; switch (dayOfWeek) { case 5: if (featureFlipper.userFeatureActive(FeatureFlipper.INSIGHTS_TESTING, accountId, Collections.EMPTY_LIST)) { LOGGER.debug("setting category to generate as wake variance"); categoryToGenerate = InsightCard.Category.WAKE_VARIANCE; break; } else { return; } case 6: if (featureFlipper.userFeatureActive(FeatureFlipper.INSIGHTS_TESTING, accountId, Collections.EMPTY_LIST)) { LOGGER.debug("setting category to generate as wake variance"); categoryToGenerate = InsightCard.Category.WAKE_VARIANCE; break; } else { return; } default: return; } if (!recentCategories.contains(categoryToGenerate)) { generateInsightsByCategory(accountId, deviceId, categoryToGenerate); } }

Target:
private void generateGeneralInsights(final Long accountId, final Long deviceId) { final Set<InsightCard.Category> recentCategories = this.getRecentInsightsCategories(accountId); final List<InsightCard.Category> eligibleCategories = new ArrayList<>(); for (final InsightCard.Category category : InsightCard.Category.values()) { if (!recentCategories.contains(category)) { eligibleCategories.add(category); } } if (eligibleCategories.isEmpty()) { LOGGER.debug("No new insights generated: {}", accountId); return; } if (!recentCategories.contains(InsightCard.Category.LIGHT)) { LOGGER.debug("Light has not been generated recently, will now generate by category"); this.generateInsightsByCategory(accountId, deviceId, InsightCard.Category.LIGHT); } else if (!recentCategories.contains(InsightCard.Category.TEMPERATURE)) { this.generateInsightsByCategory(accountId, deviceId, InsightCard.Category.TEMPERATURE); } else if (!recentCategories.contains(InsightCard.Category.SLEEP_QUALITY)) { this.generateInsightsByCategory(accountId, deviceId, InsightCard.Category.SLEEP_QUALITY); } final Integer dayOfWeek = DateTime.now().getDayOfWeek(); LOGGER.debug("The day of week is {}", dayOfWeek); InsightCard.Category categoryToGenerate; switch (dayOfWeek) { case 1: case 2: case 3: if (!featureFlipper.userFeatureActive(FeatureFlipper.INSIGHTS_WAKE_VARIANCE, accountId, Collections.EMPTY_LIST)) { return; } LOGGER.debug("setting category to generate as wake variance"); categoryToGenerate = InsightCard.Category.WAKE_VARIANCE; break; default: return; } if (!recentCategories.contains(categoryToGenerate)) { generateInsightsByCategory(accountId, deviceId, categoryToGenerate); } }
Source:
public void acknowledgeAlarm(OnmsAlarm alarm, Date now) { LOG.info("Acknowledging alarm with id: @ {}", alarm.getId(), now); final OnmsAlarm alarmInTrans = alarmDao.get(alarm.getId()); if (alarmInTrans == null) { LOG.warn("Alarm disappeared: {}. Skipping ack.", alarm); return; } OnmsAcknowledgment ack = new OnmsAcknowledgment(alarm, DEFAULT_USER, now); ack.setAckAction(AckAction.ACKNOWLEDGE); acknowledgmentDao.processAck(ack); }

Target:
public void acknowledgeAlarm(OnmsAlarm alarm, Date now) { LOG.info("Acknowledging alarm with id: @ {}", alarm.getId(), now); final OnmsAlarm alarmInTrans = alarmDao.get(alarm.getId()); if (alarmInTrans == null) { LOG.warn("Alarm disappeared: {}. Skipping ack.", alarm); return; } OnmsAcknowledgment ack = new OnmsAcknowledgment(alarmInTrans, DEFAULT_USER, now); ack.setAckAction(AckAction.ACKNOWLEDGE); acknowledgmentDao.processAck(ack); }
Source:
private void initMultiViewJobStatusTracker(Configuration config) { try { Class<?> defaultViewDeletionTrackerClass = DefaultMultiViewJobStatusTracker.class; if (config.get(PhoenixConfigurationUtil.MAPREDUCE_VIEW_TTL_MAPPER_TRACKER_CLAZZ) != null) { LOGGER.info("Using customized tracker class : " + config.get(PhoenixConfigurationUtil.MAPREDUCE_VIEW_TTL_MAPPER_TRACKER_CLAZZ)); defaultViewDeletionTrackerClass = Class.forName( config.get(PhoenixConfigurationUtil.MAPREDUCE_VIEW_TTL_MAPPER_TRACKER_CLAZZ)); } else { LOGGER.info("Using default tracker class "); } this.multiViewJobStatusTracker = (MultiViewJobStatusTracker) defaultViewDeletionTrackerClass.newInstance(); } catch (Exception e) { LOGGER.info("exception " + e.getMessage()); LOGGER.info("stack trace" + e.getStackTrace().toString()); } }

Target:
private void initMultiViewJobStatusTracker(Configuration config) throws Exception { try { Class<?> defaultViewDeletionTrackerClass = DefaultMultiViewJobStatusTracker.class; if (config.get(PhoenixConfigurationUtil.MAPREDUCE_MULTI_INPUT_MAPPER_TRACKER_CLAZZ) != null) { LOGGER.info("Using customized tracker class : " + config.get(PhoenixConfigurationUtil.MAPREDUCE_MULTI_INPUT_MAPPER_TRACKER_CLAZZ)); defaultViewDeletionTrackerClass = Class.forName( config.get(PhoenixConfigurationUtil.MAPREDUCE_MULTI_INPUT_MAPPER_TRACKER_CLAZZ)); } else { LOGGER.info("Using default tracker class "); } this.multiViewJobStatusTracker = (MultiViewJobStatusTracker) defaultViewDeletionTrackerClass.newInstance(); } catch (Exception e) { LOGGER.error("Getting exception While initializing initMultiViewJobStatusTracker with error message"); LOGGER.error("stack trace" + e.getStackTrace().toString()); throw e; } }
Source:
public void createGaugeMetric( @Suspended final AsyncResponse asyncResponse, @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo ) { if(metricDefinition.getType() != null && metricDefinition.getType() != MetricType.GAUGE) { asyncResponse.resume(badRequest(new ApiError("MetricDefinition type does not match " + MetricType .GAUGE.getText()))); } Metric<Double> metric = new Metric<>(new MetricId<>(tenantId, GAUGE, metricDefinition.getId()), metricDefinition.getTags(), metricDefinition.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/gauges/{id}").build(metric.getId().getName()); metricsService.createMetric(metric).subscribe(new MetricCreatedObserver(asyncResponse, location)); }

Target:
public void createGaugeMetric( @Suspended final AsyncResponse asyncResponse, @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo ) { if(metricDefinition.getType() != null && MetricType.GAUGE != metricDefinition.getType()) { asyncResponse.resume(badRequest(new ApiError("MetricDefinition type does not match " + MetricType .GAUGE.getText()))); } Metric<Double> metric = new Metric<>(new MetricId<>(tenantId, GAUGE, metricDefinition.getId()), metricDefinition.getTags(), metricDefinition.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/gauges/{id}").build(metric.getId().getName()); metricsService.createMetric(metric).subscribe(new MetricCreatedObserver(asyncResponse, location)); }
Source:
public Response<PageBlobItem> uploadPagesWithResponse(PageRange pageRange, InputStream body, PageBlobAccessConditions pageBlobAccessConditions, Duration timeout, Context context) { Objects.requireNonNull(body); long length = pageRange.end() - pageRange.start() + 1; Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(body, length, PAGE_BYTES); Mono<Response<PageBlobItem>> response = pageBlobAsyncClient.uploadPagesWithResponse(pageRange, fbb.subscribeOn(Schedulers.elastic()), pageBlobAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); }

Target:
public Response<PageBlobItem> uploadPagesWithResponse(PageRange pageRange, InputStream body, PageBlobAccessConditions pageBlobAccessConditions, Duration timeout, Context context) { Objects.requireNonNull(body); final long length = pageRange.end() - pageRange.start() + 1; Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(body, length, PAGE_BYTES); Mono<Response<PageBlobItem>> response = pageBlobAsyncClient.uploadPagesWithResponse(pageRange, fbb.subscribeOn(Schedulers.elastic()), pageBlobAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); }
Source:
public ViewAction<T> cloneInstance() { return new CompositeViewAction<T>(getViewId(), getTriggerType()); }

Target:
public ViewAction<T> cloneInstance() { CompositeViewAction<T> newCompositeAction = new CompositeViewAction<T>(getViewId(), getTriggerType()); for (ViewAction<T> action : actionList) { newCompositeAction.registerAction(action.cloneInstance()); } return newCompositeAction; }
Source:
public void removed(IExtension[] extensions) { for (IExtension extension : extensions) { CustomLayoutAlgorithmProvider layoutAlgorithmProvider = extensionToLayoutAlgorithmProvider.get(extension); if (layoutAlgorithmProvider != null) { List<CustomLayoutAlgorithm> customLayoutAlgorithms = layoutAlgorithmProvider.getCustomLayoutAlgorithms(); for (CustomLayoutAlgorithm customLayoutAlgorithm : customLayoutAlgorithms) { layoutProviderRegistry.remove(customLayoutAlgorithm.getId()); } } extensionToLayoutAlgorithmProvider.put(extension, null); } }

Target:
public void removed(IExtension[] extensions) { for (IExtension extension : extensions) { CustomLayoutAlgorithmProvider layoutAlgorithmProvider = extensionToLayoutAlgorithmProvider.get(extension); if (layoutAlgorithmProvider != null) { List<CustomLayoutAlgorithm> customLayoutAlgorithms = layoutAlgorithmProvider.getCustomLayoutAlgorithms(); for (CustomLayoutAlgorithm customLayoutAlgorithm : customLayoutAlgorithms) { layoutProviderRegistry.remove(customLayoutAlgorithm.getId()); } } extensionToLayoutAlgorithmProvider.remove(extension); } }
Source:
private static Map<String, List<String>> extractToMap(List<String> lines, Pattern pattern) { Map<String, List<String>> results = new HashMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); Matcher matcher = pattern.matcher(line); if (matcher.matches()) { String elementName = matcher.group("name"); if (!results.containsKey(elementName)) { results.put(elementName, new ArrayList<>()); } List<String> currentDescriptions = results.get(elementName); String elementDescription = getNextLineIfNeeded(lines, i, matcher.group("descr")); if (elementDescription != null) { currentDescriptions.add(elementDescription); } } } return results; }

Target:
private static Map<String, List<String>> extractToMap(List<String> lines, Pattern pattern) { Map<String, List<String>> results = new HashMap<>(); for (int i = 0; i < lines.size(); i++) { Matcher matcher = pattern.matcher(lines.get(i)); if (matcher.matches()) { List<String> descriptions = results.computeIfAbsent(matcher.group("name"), key -> new ArrayList<>()); String newDescription = getNextLineIfNeeded(lines, i, matcher.group("descr")); if (newDescription != null) { descriptions.add(newDescription); } } } return results; }
Source:
public void testCatalogLeaksBundlesToReferencedYaml() throws Exception { String parentCatalogId = "my.catalog.app.id.url.parent"; addCatalogItem( "brooklyn.catalog:", " id: " + parentCatalogId, " libraries:", " - url: " + OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL, "", "services:", "- type: classpath:/yaml-ref-bundle-without-libraries.yaml"); Entity app = createAndStartApplication( "services:", "- type: " + parentCatalogId); Collection<Entity> children = app.getChildren(); Assert.assertEquals(children.size(), 1); Entity child = Iterables.getOnlyElement(children); Assert.assertEquals(child.getEntityType().getName(), "brooklyn.osgi.tests.SimpleEntity"); deleteCatalogEntity(parentCatalogId); }

Target:
public void testCatalogLeaksBundlesToReferencedYaml() throws Exception { String parentCatalogId = "my.catalog.app.id.url.parent"; addCatalogItem( "brooklyn.catalog:", " id: " + parentCatalogId, " libraries:", " - url: " + OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL, "", "services:", "- type: classpath://yaml-ref-bundle-without-libraries.yaml"); Entity app = createAndStartApplication( "services:", "- type: " + parentCatalogId); Collection<Entity> children = app.getChildren(); Assert.assertEquals(children.size(), 1); Entity child = Iterables.getOnlyElement(children); Assert.assertEquals(child.getEntityType().getName(), "brooklyn.osgi.tests.SimpleEntity"); deleteCatalogEntity(parentCatalogId); }
Source:
public Object asJSON(Object value) { byte[] bytes; if(Boolean.class.isAssignableFrom(value.getClass())){ bytes = new byte[]{(byte) ((Boolean)value?1:0)}; }else { bytes = (byte[]) value; } if ( bytes.length == 8 && ((bytes[7] & 0xFF) > 127) ) { return bytesToBigInteger(bytes); } else { return bytesToLong(bytes); } }

Target:
public Object asJSON(Object value) { byte[] bytes; if( value instanceof Boolean ){ bytes = new byte[]{(byte) (( Boolean ) value ? 1 : 0)}; }else { bytes = (byte[]) value; } if ( bytes.length == 8 && ((bytes[7] & 0xFF) > 127) ) { return bytesToBigInteger(bytes); } else { return bytesToLong(bytes); } }
Source:
private DirectDownloadCommand getDirectDownloadCommandFromProtocol(DownloadProtocol protocol, String url, Long templateId, PrimaryDataStoreTO destPool, String checksum, Map<String, String> httpHeaders) { int connectTimeout = DEFAULT_DIRECT_DOWNLOAD_CONNECT_TIMEOUT; int soTimeout = DEFAULT_DIRECT_DOWNLOAD_SOCKET_TIMEOUT; int connectionRequestTimeout = DEFAULT_DIRECT_DOWNLOAD_CONNECTION_REQUEST_TIMEOUT; if (DownloadProtocol.HTTP.equals(protocol) || DownloadProtocol.HTTPS.equals(protocol) || DownloadProtocol.METALINK.equals(protocol)) { try { connectTimeout = Integer.parseInt(configDao.getValue(DirectDownloadConnectTimeout.key())); } catch (NumberFormatException nfe) { s_logger.warn(String.format("Unable to retrieve configuration: %s value", DirectDownloadConnectTimeout.key()), nfe); } try { soTimeout = Integer.parseInt(configDao.getValue(DirectDownloadSocketTimeout.key())); } catch (NumberFormatException nfe) { s_logger.warn(String.format("Unable to retrieve configuration: %s value", DirectDownloadSocketTimeout.key()), nfe); } } if (DownloadProtocol.HTTPS.equals(protocol)) { try { connectionRequestTimeout = Integer.parseInt(configDao.getValue(DirectDownloadConnectionRequestTimeout.key())); } catch (NumberFormatException nfe) { s_logger.warn(String.format("Unable to retrieve configuration: %s value", DirectDownloadConnectionRequestTimeout.key()), nfe); } } if (protocol.equals(DownloadProtocol.HTTP)) { return new HttpDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders, connectTimeout, soTimeout); } else if (protocol.equals(DownloadProtocol.HTTPS)) { return new HttpsDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders, connectTimeout, soTimeout, connectionRequestTimeout); } else if (protocol.equals(DownloadProtocol.NFS)) { return new NfsDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders); } else if (protocol.equals(DownloadProtocol.METALINK)) { return new MetalinkDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders, connectTimeout, soTimeout); } else { return null; } }

Target:
private DirectDownloadCommand getDirectDownloadCommandFromProtocol(DownloadProtocol protocol, String url, Long templateId, PrimaryDataStoreTO destPool, String checksum, Map<String, String> httpHeaders) { int connectTimeout = DirectDownloadConnectTimeout.value(); int soTimeout = DirectDownloadSocketTimeout.value(); int connectionRequestTimeout = DirectDownloadConnectionRequestTimeout.value(); if (protocol.equals(DownloadProtocol.HTTP)) { return new HttpDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders, connectTimeout, soTimeout); } else if (protocol.equals(DownloadProtocol.HTTPS)) { return new HttpsDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders, connectTimeout, soTimeout, connectionRequestTimeout); } else if (protocol.equals(DownloadProtocol.NFS)) { return new NfsDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders); } else if (protocol.equals(DownloadProtocol.METALINK)) { return new MetalinkDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders, connectTimeout, soTimeout); } else { return null; } }
Source:
public synchronized void stopListener() { closeListenerSockets(); while(connections.size() > 0) { Socket conn = connections.get(0); try { conn.close(); } catch (Exception e) { tsLogger.i18NLogger.warn_could_not_close_transaction_listener_connection(conn, e); } try { wait(); } catch (InterruptedException ignoredIe) { tsLogger.logger.debug("Waiting for connection close was interrupted", ignoredIe); } } try { this.join(); } catch (InterruptedException ignoredIe) { tsLogger.logger.debug("Waiting to ensure the listener thread has exited was interrupted", ignoredIe); } }

Target:
public synchronized void stopListener() { closeListenerSockets(); while(connections.size() > 0) { Socket conn = connections.get(0); try { conn.close(); } catch (Exception e) { tsLogger.i18NLogger.warn_could_not_close_transaction_listener_connection(conn, e); } try { wait(); } catch (InterruptedException ie) { tsLogger.logger.debug("Waiting for connection close was interrupted", ie); } } try { this.join(); } catch (InterruptedException ie) { tsLogger.logger.debug("Waiting to ensure the listener thread has exited was interrupted", ie); } }
Source:
public Date getEndDate() { return new Date(endDate.getTime()); }

Target:
public Date getEndDate() { return (Date) endDate.clone(); }
Source:
VoltTableSpliterator(VoltTable table, int origin, int fence) { System.out.printf("New VTS %d -> %d in Table with %d rows\n", origin, fence, table.getRowCount()); System.out.flush(); if (origin == fence) { m_row = null; return; } assert(origin < fence); m_row = table.fetchRow(origin); m_fence = fence; }

Target:
VoltTableSpliterator(VoltTable table, int origin, int fence) { m_fence = fence; if (origin == fence) { m_row = null; return; } assert(origin < fence); m_row = table.fetchRow(origin); }
Source:
public void testSingleStream() throws Exception { List<Type> types = ImmutableList.of(INTEGER, INTEGER); MaterializedResult actual = mergeSortedPages( types, ImmutableList.of(0, 1), ImmutableList.of(ASC_NULLS_FIRST, ASC_NULLS_FIRST), ImmutableList.of( rowPagesBuilder(types) .row(1, 1) .row(2, 2) .pageBreak() .row(3, 3) .row(4, 4) .build()), new Duration(50, MILLISECONDS), executor); MaterializedResult expected = resultBuilder(TEST_SESSION, types) .row(1, 1) .row(2, 2) .row(3, 3) .row(4, 4) .build(); assertEquals(actual, expected); }

Target:
public void testSingleStream() throws Exception { List<Type> types = ImmutableList.of(INTEGER, INTEGER); MaterializedResult actual = mergeSortedPages( types, ImmutableList.of(0, 1), ImmutableList.of(ASC_NULLS_FIRST, DESC_NULLS_FIRST), ImmutableList.of( rowPagesBuilder(types) .row(1, 4) .row(2, 3) .pageBreak() .row(3, 2) .row(4, 1) .build()), new Duration(50, MILLISECONDS), executor); MaterializedResult expected = resultBuilder(TEST_SESSION, types) .row(1, 4) .row(2, 3) .row(3, 2) .row(4, 1) .build(); assertEquals(actual, expected); }
Source:
public FacebookAuth(Activity activity) { super(activity); callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { if (callback != null) { callback.onLogin(loginResult.getAccessToken().getToken()); } logger.debug("Facebook Logged in successfully."); } @Override public void onCancel() { logger.debug("Facebook Log in canceled."); } @Override public void onError(FacebookException error) { logger.debug("Facebook Log in got error."); } }); }

Target:
public FacebookAuth(Activity activity) { super(activity); callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { if (callback != null) { callback.onLogin(loginResult.getAccessToken().getToken()); } logger.debug("Facebook Logged in successfully."); } @Override public void onCancel() { logger.debug("Facebook Log in canceled."); } @Override public void onError(FacebookException error) { logger.error(error); } }); }
Source:
public void testOneNodeDiesOnRequest() throws Exception { CountDownLatch nodeStopLatch = new CountDownLatch(1); Ignite srv1 = startGrid(0); replaceWithStoppingMappingRequestListener( ((GridKernalContext)U.field(srv1, "ctx")).io(), 0, nodeStopLatch); Ignite srv2 = startGrid(1); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv2, "ctx")).io()); Ignite srv3 = startGrid(2); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv3, "ctx")).io()); srv3.cache(DEFAULT_CACHE_NAME).put( 1, new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA")); clientMode = true; Ignite cl1 = startClientGrid(4); cl1.cache(DEFAULT_CACHE_NAME).get(1); nodeStopLatch.await(5_000, TimeUnit.MILLISECONDS); int result = mappingReqsCounter.get(); assertEquals("Expected requests count is 2, actual is " + result, 2, result); }

Target:
public void testOneNodeDiesOnRequest() throws Exception { CountDownLatch nodeStopLatch = new CountDownLatch(1); Ignite srv1 = startGrid(0); replaceWithStoppingMappingRequestListener( ((GridKernalContext)U.field(srv1, "ctx")).io(), 0, nodeStopLatch); Ignite srv2 = startGrid(1); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv2, "ctx")).io()); Ignite srv3 = startGrid(2); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv3, "ctx")).io()); srv3.cache(DEFAULT_CACHE_NAME).put( 1, new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA")); Ignite cl1 = startClientGrid(4); cl1.cache(DEFAULT_CACHE_NAME).get(1); nodeStopLatch.await(5_000, TimeUnit.MILLISECONDS); int result = mappingReqsCounter.get(); assertEquals("Expected requests count is 2, actual is " + result, 2, result); }
Source:
protected void executeCommand() { for (Guid templateGuid : getTemplatesList()) { VmTemplate template = DbFacade.getInstance().getVmTemplateDao().get(templateGuid); if (DbFacade.getInstance().getTagDao().getTagTemplateByTagIdAndByTemplateId(getTagId(), templateGuid) == null) { if (template != null) { appendCustomValue("TemplatesNames", template.getName(), ", "); TagsTemplateMap map = new TagsTemplateMap(getTagId(), templateGuid); DbFacade.getInstance().getTagDao().attachTemplateToTag(map); noActionDone = false; } } else { if (template != null) { appendCustomValue("TemplatesNamesExists", template.getName(), ", "); } } } setSucceeded(true); }

Target:
protected void executeCommand() { for (Guid templateGuid : getTemplatesList()) { VmTemplate template = DbFacade.getInstance().getVmTemplateDao().get(templateGuid); if (template != null) { if (DbFacade.getInstance().getTagDao().getTagTemplateByTagIdAndByTemplateId(getTagId(), templateGuid) == null) { appendCustomValue("TemplatesNames", template.getName(), ", "); TagsTemplateMap map = new TagsTemplateMap(getTagId(), templateGuid); DbFacade.getInstance().getTagDao().attachTemplateToTag(map); noActionDone = false; } else { appendCustomValue("TemplatesNamesExists", template.getName(), ", "); } } } setSucceeded(true); }
Source:
public void verifyAdditionalPropertyIntegerResponse() throws Exception { Map<String, String> queryParams = new HashMap<String, String>(); String str = client.invokeAPI("/mockResponses/additionalProperties1", "GET", queryParams, null, new HashMap<String, String>(), null, "application/json", null, new String[0]); assertEquals(str, "{\"key\":\"key\",\"value\":{\"bar\":0}}"); }

Target:
public void verifyAdditionalPropertyIntegerResponse() throws Exception { Map<String, String> queryParams = new HashMap<String, String>(); String str = client.invokeAPI("/mockResponses/additionalProperties1", "GET", queryParams, null, new HashMap<String, String>(), null, "application/json", null, new String[0]); assertEquals(str, "{\"foo\":0,\"additionalProperty\":{\"bar\":0}}"); }