auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testLinkPropertiesWithWakeOnLanForActiveNetwork() throws Exception { mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI); LinkProperties wifiLp = new LinkProperties(); wifiLp.setInterfaceName(WIFI_WOL_IFNAME); wifiLp.setWakeOnLanEnabled(true); mWiFiNetworkAgent.connect(false); mWiFiNetworkAgent.sendLinkProperties(wifiLp); waitForIdle(); assertEquals(wifiLp, mService.getActiveLinkProperties()); reset(mStatsService); }

Target:
public void testLinkPropertiesWithWakeOnLanForActiveNetwork() throws Exception { mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI); LinkProperties wifiLp = new LinkProperties(); wifiLp.setInterfaceName(WIFI_WOL_IFNAME); wifiLp.setWakeOnLanEnabled(false); mWiFiNetworkAgent.connect(false); mWiFiNetworkAgent.sendLinkProperties(wifiLp); waitForIdle(); wifiLp.setWakeOnLanEnabled(true); assertEquals(wifiLp, mService.getActiveLinkProperties()); }
Source:
public Iterator<String> call(Integer partition, Iterator<T> locatedRowIterator) throws Exception { taskContext = TaskContext.get(); if (taskContext != null && taskContext.attemptNumber() > 0) { LOG.trace("KS.c attempts "+taskContext.attemptNumber()); long entriesInKafka = KafkaUtils.messageCount(bootstrapServers, topicName, partition); LOG.trace("KS.c entries "+entriesInKafka); for (long i = 0; i < entriesInKafka; ++i) { locatedRowIterator.next(); } } Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); props.put(ProducerConfig.CLIENT_ID_CONFIG, "spark-producer-dss-ks-"+UUID.randomUUID() ); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ExternalizableSerializer.class.getName()); KafkaProducer<Integer, Externalizable> producer = new KafkaProducer<>(props); int count = 0 ; while (locatedRowIterator.hasNext()) { T lr = locatedRowIterator.next(); if(schema.isPresent() && lr instanceof ValueRow) { lr = ((T)new ValueRow((ValueRow)lr, schema)); } ProducerRecord<Integer, Externalizable> record = new ProducerRecord(topicName, count++, lr); producer.send(record); LOG.trace("KS.c sent "+partition.intValue()+" "+count+" "+lr); } LOG.trace("KS.c count "+partition.intValue()+" "+count); producer.close(); return Arrays.asList("OK").iterator(); }

Target:
public Iterator<String> call(Integer partition, Iterator<T> locatedRowIterator) throws Exception { taskContext = TaskContext.get(); if (taskContext != null && taskContext.attemptNumber() > 0) { LOG.trace("KS.c attempts "+taskContext.attemptNumber()); long entriesInKafka = KafkaUtils.messageCount(bootstrapServers, topicName, partition); LOG.trace("KS.c entries "+entriesInKafka); for (long i = 0; i < entriesInKafka; ++i) { locatedRowIterator.next(); } } Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); props.put(ProducerConfig.CLIENT_ID_CONFIG, "spark-producer-dss-ks-"+UUID.randomUUID() ); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ExternalizableSerializer.class.getName()); KafkaProducer<Integer, Externalizable> producer = new KafkaProducer<>(props); int count = 0 ; while (locatedRowIterator.hasNext()) { T lr = locatedRowIterator.next(); ProducerRecord<Integer, Externalizable> record = new ProducerRecord(topicName, count++, lr); producer.send(record); LOG.trace("KS.c sent "+partition.intValue()+" "+count+" "+lr); } LOG.trace("KS.c count "+partition.intValue()+" "+count); producer.close(); return Arrays.asList("OK").iterator(); }
Source:
public static Block createTestBlock() { BlockBuilder blockBuilder = IPADDRESS.createBlockBuilder(null, 1); Slice slice = Slices.wrappedBuffer(InetAddresses.forString("2001:db8::ff00:42:8328").getAddress()); IPADDRESS.writeSlice(blockBuilder, slice); return blockBuilder.build(); }

Target:
public static Block createTestBlock() { BlockBuilder blockBuilder = IPADDRESS.createBlockBuilder(null, 1); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8320")); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8321")); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8322")); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8323")); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8324")); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8325")); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8326")); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8327")); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8328")); IPADDRESS.writeSlice(blockBuilder, getSliceForAddress("2001:db8::ff00:42:8329")); return blockBuilder.build(); }
Source:
void updateSelectedOrganizationalUnit() { libraryService.call( new RemoteCallback<OrganizationalUnitRepositoryInfo>() { @Override public void callback( final OrganizationalUnitRepositoryInfo newInfo ) { refreshLibrary( newInfo ); } } ).getOrganizationalUnitRepositoryInfo( getViewSelectedOrganizationalUnit() ); }

Target:
void updateSelectedOrganizationalUnit() { libraryService.call( ( OrganizationalUnitRepositoryInfo newInfo ) -> refreshLibrary( newInfo ) ) .getOrganizationalUnitRepositoryInfo( getViewSelectedOrganizationalUnit() ); }
Source:
ParsedDockerComposeFile(File composeFile) { Yaml yaml = new Yaml(); try (FileInputStream fileInputStream = FileUtils.openInputStream(composeFile)) { composeFileContent = yaml.load(fileInputStream); } catch (Exception e) { throw new IllegalStateException("Unable to parse YAML file from " + composeFile.getAbsolutePath(), e); } this.composeFileName = composeFile.getAbsolutePath(); parseAndValidate(); }

Target:
ParsedDockerComposeFile(File composeFile) { Yaml yaml = new Yaml(); try (FileInputStream fileInputStream = FileUtils.openInputStream(composeFile)) { composeFileContent = yaml.load(fileInputStream); } catch (Exception e) { throw new IllegalArgumentException("Unable to parse YAML file from " + composeFile.getAbsolutePath(), e); } this.composeFileName = composeFile.getAbsolutePath(); parseAndValidate(); }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = getPermissionList(getParameters().getEvent()); if (hasHostExternalStatus()) { permissionList.add(new PermissionSubject(new Guid(getParameters().getEvent().getVdsId().toString()), VdcObjectType.VDS, ActionGroup.EDIT_HOST_CONFIGURATION)); } return permissionList; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = getPermissionList(getParameters().getEvent()); if (hasHostExternalStatus()) { permissionList.add(new PermissionSubject(getParameters().getEvent().getVdsId(), VdcObjectType.VDS, ActionGroup.EDIT_HOST_CONFIGURATION)); } return permissionList; }
Source:
public void testDeactivateStorageDomainWithRunningVmWithLeaseFails() { VmStatic vm = new VmStatic(); vm.setName("myRunningVmWithLease"); mockDomain(); when(vmStaticDao.getAllRunningWithLeaseOnForStorageDomain(domain.getId())).thenReturn(Collections.singletonList(vm)); ValidateTestUtils.runAndAssertValidateFailure(cmd, EngineMessage.ERROR_CANNOT_DEACTIVATE_DOMAIN_WITH_RUNNING_VMS_WITH_LEASES); assertTrue(cmd.getReturnValue().getValidationMessages().contains(String.format("$vmNames %s", vm.getName()))); }

Target:
public void testDeactivateStorageDomainWithRunningVmWithLeaseFails() { VmStatic vm = new VmStatic(); vm.setName("myRunningVmWithLease"); mockDomain(); when(vmStaticDao.getAllRunningWithLeaseOnStorageDomain(domain.getId())).thenReturn(Collections.singletonList(vm)); ValidateTestUtils.runAndAssertValidateFailure(cmd, EngineMessage.ERROR_CANNOT_DEACTIVATE_DOMAIN_WITH_RUNNING_VMS_WITH_LEASES); assertTrue(cmd.getReturnValue().getValidationMessages().contains(String.format("$vmNames %s", vm.getName()))); }
Source:
public static Type merge( Type t1, Type t2 ) { NativeType nativeType = t1.nativeType(); Range cardinality = t1.cardinality(); Map< String, Type > subTypes = new HashMap< String, Type >(); for( Entry< String, Type > entry : t1.subTypes().entrySet()) { subTypes.put( entry.getKey(), entry.getValue() ); } if ( t2 != null ) { for( Entry< String, Type > entry : t2.subTypes().entrySet() ) { subTypes.put( entry.getKey(), entry.getValue() ); } } return create( nativeType, cardinality, false, subTypes ); }

Target:
public static Type merge( Type t1, Type t2 ) { final NativeType nativeType = t1.nativeType(); final Range cardinality = t1.cardinality(); final Map< String, Type > subTypes = new HashMap<>(); for( Entry< String, Type > entry : t1.subTypes().entrySet() ) { subTypes.put( entry.getKey(), entry.getValue() ); } if ( t2 != null ) { for( Entry< String, Type > entry : t2.subTypes().entrySet() ) { subTypes.put( entry.getKey(), entry.getValue() ); } } return create( nativeType, cardinality, false, subTypes ); }
Source:
private boolean shouldExecute() { if (!buildContext.isIncremental()) { return true; } if (buildContext.hasDelta(new File(workingDirectory, "Gruntfile.js"))) { return true; } if (srcdir == null) { getLog().info("grunt goal doesn't have srcdir set: not checking for modified files"); return true; } Scanner scanner = buildContext.newScanner(srcdir); scanner.scan(); String[] includedFiles = scanner.getIncludedFiles(); return (includedFiles != null && includedFiles.length > 0); }

Target:
private boolean shouldExecute() { if (buildContext == null || !buildContext.isIncremental()) { return true; } if (triggerfiles != null) { for (int i = 0; i < triggerfiles.length; i++) { if (buildContext.hasDelta(triggerfiles[i])) { return true; } } } else { if (buildContext.hasDelta(new File(workingDirectory, "Gruntfile.js"))) { return true; } } if (srcdir == null) { getLog().info("grunt goal doesn't have srcdir set: not checking for modified files"); return true; } Scanner scanner = buildContext.newScanner(srcdir); scanner.scan(); String[] includedFiles = scanner.getIncludedFiles(); return (includedFiles != null && includedFiles.length > 0); }
Source:
private static long sleepAndGetNextBackoffTime(long sleepTime) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.throwUncheckedException(e); } return Math.min(sleepTime * 2, MAX_SLEEP_TIME); }

Target:
private static long sleepAndGetNextBackoffTime(long sleepTime) { try { long wait = sleepTime + (long) (sleepTime * getRandomJitter()); log.info("Disagreement on schema versions, waiting for ms and retrying.", SafeArg.of("backoff", wait)); Thread.sleep(wait); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.throwUncheckedException(e); } return Math.min(sleepTime * 2, MAX_SLEEP_TIME); }
Source:
public void registerAlias(PathElement address, AliasEntry alias) { RootInvocation rootInvocation = parent == null ? null : getRootInvocation(); AbstractResourceRegistration root = rootInvocation == null ? this : rootInvocation.root; PathAddress myaddr = rootInvocation == null ? PathAddress.EMPTY_ADDRESS : rootInvocation.pathAddress; assert alias.getTarget() instanceof AbstractResourceRegistration : "Unknown alias type"; PathAddress targetAddress = alias.getTarget().getPathAddress(); alias.setAddresses(targetAddress, myaddr.append(address)); AbstractResourceRegistration target = (AbstractResourceRegistration)root.getSubModel(alias.getTargetAddress()); if (target == null) { throw ControllerLogger.ROOT_LOGGER.aliasTargetResourceRegistrationNotFound(alias.getTargetAddress()); } registerAlias(address, alias, target); }

Target:
public void registerAlias(PathElement address, AliasEntry alias) { RootInvocation rootInvocation = parent == null ? null : getRootInvocation(); AbstractResourceRegistration root = rootInvocation == null ? this : rootInvocation.root; PathAddress myaddr = rootInvocation == null ? PathAddress.EMPTY_ADDRESS : rootInvocation.pathAddress; PathAddress targetAddress = alias.getTarget().getPathAddress(); alias.setAddresses(targetAddress, myaddr.append(address)); AbstractResourceRegistration target = (AbstractResourceRegistration)root.getSubModel(alias.getTargetAddress()); if (target == null) { throw ControllerLogger.ROOT_LOGGER.aliasTargetResourceRegistrationNotFound(alias.getTargetAddress()); } registerAlias(address, alias, target); }
Source:
private void applyContaminationFilter(final M2FiltersArgumentCollection MTFAC, final VariantContext vc, final Collection<String> filters) { if (vc.hasAttribute(VCFConstants.ALLELE_FREQUENCY_KEY)) { final double[] alleleFrequencies = getArrayAttribute(vc, VCFConstants.ALLELE_FREQUENCY_KEY); final double maxFrequency = MathUtils.arrayMax(alleleFrequencies); if (maxFrequency < contamination) { filters.add(CONTAMINATION_FILTER_NAME); } } }

Target:
private void applyContaminationFilter(final M2FiltersArgumentCollection MTFAC, final VariantContext vc, final Collection<String> filters) { final Genotype tumorGenotype = vc.getGenotype(tumorSample); final double[] alleleFractions = GATKProtectedVariantContextUtils.getAttributeAsDoubleArray(tumorGenotype, VCFConstants.ALLELE_FREQUENCY_KEY, () -> new double[] {1.0}, 1.0); final double maxFraction = MathUtils.arrayMax(alleleFractions); if (maxFraction < contamination) { filters.add(CONTAMINATION_FILTER_NAME); } }
Source:
public HungryLynx(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{G}"); this.subtype.add(SubType.CAT); this.power = new MageInt(2); this.toughness = new MageInt(2); Effect effect = new GainAbilityAllEffect(new ProtectionAbility(filterProRat), Duration.WhileOnBattlefield, filterCat); effect.setText("Cats you control have protection from Rats. <i>(They can't be blocked, targeted, or dealt damage by Rats.)</i>"); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, effect)); Ability ability = new BeginningOfEndStepTriggeredAbility(Zone.BATTLEFIELD, new CreateTokenTargetEffect(new DeathtouchRatToken()), TargetController.YOU, null, false); Target target = new TargetOpponent(); ability.addTarget(target); this.addAbility(ability); Effect effect2 = new AddCountersAllEffect(CounterType.P1P1.createInstance(), filterCat); effect2.setText(" put a +1/+1 counter on each Cat you control."); this.addAbility(new DiesCreatureTriggeredAbility(effect2, false, filterRat)); }

Target:
public HungryLynx(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{G}"); this.subtype.add(SubType.CAT); this.power = new MageInt(2); this.toughness = new MageInt(2); Effect effect = new GainAbilityAllEffect(new ProtectionAbility(filterProRat), Duration.WhileOnBattlefield, filterCat); effect.setText("Cats you control have protection from Rats. <i>(They can't be blocked, targeted, or dealt damage by Rats.)</i>"); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, effect)); Ability ability = new BeginningOfEndStepTriggeredAbility(Zone.BATTLEFIELD, new CreateTokenTargetEffect(new DeathtouchRatToken()), TargetController.YOU, null, false); Target target = new TargetOpponent(); ability.addTarget(target); this.addAbility(ability); Effect effect2 = new AddCountersAllEffect(CounterType.P1P1.createInstance(), filterCat); effect2.setText("put a +1/+1 counter on each Cat you control"); this.addAbility(new DiesCreatureTriggeredAbility(effect2, false, filterRat)); }
Source:
public void testScaleDenominator() throws Exception { LayerGroupInfo info = getCatalog().getLayerGroupByName("cascaded_group"); LayerInfo groupLayer2 = getCatalog().getLayerByName("group_lyr_2"); assertNotNull(info); assertNotNull(groupLayer2); ReferencedEnvelope request1 = new ReferencedEnvelope(groupLayer2.getResource().getNativeBoundingBox()); String lyrBBox = request1.getMinX() + "," + request1.getMinY() + "," + request1.getMaxX() + "," + request1.getMaxY(); WMSLayerInfo groupLayer1WMSResource = (WMSLayerInfo) getCatalog().getLayerByName("group_lyr_1").getResource(); groupLayer1WMSResource.setMinScale(1); groupLayer1WMSResource.setMaxScale(1000); getCatalog().save(groupLayer1WMSResource); String getMapRequest = "wms?service=WMS&version=1.1.0" + "&request=GetMap" + "&layers=" + info.getName() + "&bbox=" + lyrBBox + "&width=768&height=537&srs=EPSG:4326&Format=image/png"; BufferedImage response = getAsImage(getMapRequest, "image/png"); assertNotNull(response); groupLayer1WMSResource.setMinScale(null); groupLayer1WMSResource.setMaxScale(null); getCatalog().save(groupLayer1WMSResource); }

Target:
public void testScaleDenominator() throws Exception { LayerGroupInfo info = getCatalog().getLayerGroupByName("cascaded_group"); LayerInfo groupLayer2 = getCatalog().getLayerByName("group_lyr_2"); assertNotNull(info); assertNotNull(groupLayer2); ReferencedEnvelope request1 = new ReferencedEnvelope(groupLayer2.getResource().getNativeBoundingBox()); String lyrBBox = request1.getMinX() + "," + request1.getMinY() + "," + request1.getMaxX() + "," + request1.getMaxY(); WMSLayerInfo groupLayer1WMSResource = (WMSLayerInfo) getCatalog().getLayerByName("group_lyr_1").getResource(); groupLayer1WMSResource.setMinScale(1d); groupLayer1WMSResource.setMaxScale(1000d); getCatalog().save(groupLayer1WMSResource); String getMapRequest = "wms?service=WMS&version=1.1.0" + "&request=GetMap" + "&layers=" + info.getName() + "&bbox=" + lyrBBox + "&width=768&height=537&srs=EPSG:4326&Format=image/png"; try { BufferedImage response = getAsImage(getMapRequest, "image/png"); assertNotNull(response); } finally { groupLayer1WMSResource.setMinScale(null); groupLayer1WMSResource.setMaxScale(null); getCatalog().save(groupLayer1WMSResource); } }
Source:
public boolean resolve(Game game) { if (ability.getTargets().stillLegal(ability, game) || !canFizzle()) { game.fireEvent(new GameEvent(GameEvent.EventType.RESOLVED_ABILITY, ability.getOriginalId(), ability.getSourceId(), ability.getControllerId())); boolean result = ability.resolve(game); game.getStack().remove(this, game); return result; } if (!game.isSimulation()) { game.informPlayers("Ability has been fizzled: " + getRule()); } counter(null, game); game.getStack().remove(this, game); return false; }

Target:
public boolean resolve(Game game) { if (ability.getTargets().stillLegal(ability, game) || !canFizzle()) { boolean result = ability.resolve(game); game.getStack().remove(this, game); return result; } if (!game.isSimulation()) { game.informPlayers("Ability has been fizzled: " + getRule()); } counter(null, game); game.getStack().remove(this, game); return false; }
Source:
private void UpdateSpmPriority(Integer value) { List<EntityModel> items = new ArrayList<EntityModel>(); if (value == null) { value = defaultSpmPriority; } int neverValue = -1; EntityModel neverItem = new EntityModel("Never", neverValue); items.add(neverItem); int lowValue = defaultSpmPriority / 2; items.add(new EntityModel("Low", lowValue)); items.add(new EntityModel("Normal", defaultSpmPriority)); int highValue = defaultSpmPriority + (maxSpmPriority - defaultSpmPriority) / 2; items.add(new EntityModel("High", highValue)); EntityModel selectedItem = null; int[] values = new int[] { neverValue, lowValue, defaultSpmPriority, highValue, maxSpmPriority + 1 }; Integer prevValue = null; for (int i = 0; i < values.length; i++) { int currentValue = values[i]; if (value == currentValue) { selectedItem = items.get(i); break; } else if (prevValue != null && value > prevValue && value < currentValue) { EntityModel customItem = new EntityModel("Custom", value); items.add(i, customItem); selectedItem = customItem; break; } prevValue = currentValue; } if (selectedItem != neverItem) { items.remove(neverItem); } getSpmPriority().setItems(items); getSpmPriority().setSelectedItem(selectedItem); }

Target:
private void UpdateSpmPriority(Integer value) { List<EntityModel> items = new ArrayList<EntityModel>(); if (value == null) { value = defaultSpmPriority; } int neverValue = -1; EntityModel neverItem = new EntityModel("Never", neverValue); items.add(neverItem); int lowValue = defaultSpmPriority / 2; items.add(new EntityModel("Low", lowValue)); items.add(new EntityModel("Normal", defaultSpmPriority)); int highValue = defaultSpmPriority + (maxSpmPriority - defaultSpmPriority) / 2; items.add(new EntityModel("High", highValue)); EntityModel selectedItem = null; int[] values = new int[] { neverValue, lowValue, defaultSpmPriority, highValue, maxSpmPriority + 1 }; Integer prevValue = null; for (int i = 0; i < values.length; i++) { int currentValue = values[i]; if (value == currentValue) { selectedItem = items.get(i); break; } else if (prevValue != null && value > prevValue && value < currentValue) { EntityModel customItem = new EntityModel("Custom (" + value + ")", value); items.add(i, customItem); selectedItem = customItem; break; } prevValue = currentValue; } if (selectedItem != neverItem) { items.remove(neverItem); } getSpmPriority().setItems(items); getSpmPriority().setSelectedItem(selectedItem); }
Source:
public CTFCallsite(String en, String func, long ip, String fn, long line) { fEventName = en; fFileName = fn; fFunctionName = func; this.fIp = ip; this.fLineNumber = line; }

Target:
public CTFCallsite(String en, String func, long ip, String fn, long line) { fEventName = en; fFileName = fn; fFunctionName = func; fIp = ip; fLineNumber = line; }
Source:
public void testLogFrameworkEventType() throws Exception { final AtomicReference<LogEntry> event = new AtomicReference<LogEntry>(); final CountDownLatch countDown = new CountDownLatch(2); final Bundle b = getContext().getBundle(); LogListener listener = new LogListener() { @Override public void logged(LogEntry entry) { if (b.equals(entry.getBundle())) { event.set(entry); countDown.countDown(); } } }; reader.addLogListener(listener); b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, b.adapt(Module.class), new Exception()); countDown.await(10, TimeUnit.MILLISECONDS); assertNotNull("No event.", event.get()); assertEquals("Wrong type.", LogService.LOG_ERROR, event.get().getLevel()); b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.WARNING, b.adapt(Module.class), new Exception()); countDown.await(10, TimeUnit.MILLISECONDS); assertNotNull("No event.", event.get());; assertEquals("Wrong type.", LogService.LOG_WARNING, event.get().getLevel()); }

Target:
public void testLogFrameworkEventType() throws Exception { final List<LogEntry> events = new CopyOnWriteArrayList<LogEntry>(); final CountDownLatch countDown = new CountDownLatch(2); final Bundle b = getContext().getBundle(); LogListener listener = new LogListener() { @Override public void logged(LogEntry entry) { if (b.equals(entry.getBundle())) { events.add(entry); countDown.countDown(); } } }; reader.addLogListener(listener); b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, b.adapt(Module.class), new Exception()); b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.WARNING, b.adapt(Module.class), new Exception()); countDown.await(2, TimeUnit.SECONDS); assertEquals("Wrong number of events", 2, events.size()); assertEquals("Wrong type.", LogService.LOG_ERROR, events.get(0).getLevel()); assertEquals("Wrong type.", LogService.LOG_WARNING, events.get(1).getLevel()); }
Source:
public void testCachesResultAfterFirstLookup() throws Exception { ClassLoader ctx_loader = Thread.currentThread().getContextClassLoader(); final AtomicInteger load_count = new AtomicInteger(0); Thread.currentThread().setContextClassLoader(new ClassLoader(ctx_loader) { @Override public InputStream getResourceAsStream(String s) { InputStream in = super.getResourceAsStream(s); load_count.incrementAndGet(); return in; } }); findSqlOnClasspath("caches-result-after-first-lookup"); assertThat(load_count.get()).isEqualTo(1); findSqlOnClasspath("caches-result-after-first-lookup"); assertThat(load_count.get()).isEqualTo(1); Thread.currentThread().setContextClassLoader(ctx_loader); }

Target:
public void testCachesResultAfterFirstLookup() throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final AtomicInteger loadCount = new AtomicInteger(0); Thread.currentThread().setContextClassLoader(new ClassLoader(classLoader) { @Override public InputStream getResourceAsStream(String s) { InputStream in = super.getResourceAsStream(s); loadCount.incrementAndGet(); return in; } }); findSqlOnClasspath("caches-result-after-first-lookup"); assertThat(loadCount.get()).isEqualTo(1); findSqlOnClasspath("caches-result-after-first-lookup"); assertThat(loadCount.get()).isEqualTo(1); Thread.currentThread().setContextClassLoader(classLoader); }
Source:
private Object deserializePayload(byte[] bytes, MimeType contentType) { if (TEXT_PLAIN.equals(contentType) || APPLICATION_JSON.equals(contentType)) { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new SerializationFailedException("unable to deserialize [java.lang.String]. Encoding not supported.", e); } } else { String className = JavaClassMimeTypeConversion.classNameFromMimeType(contentType); try { Class<?> targetType = this.payloadTypeCache.get(className); if (targetType == null) { targetType = ClassUtils.forName(className, null); this.payloadTypeCache.put(className, targetType); } return this.codec.decode(bytes, targetType); } catch (ClassNotFoundException e) { throw new SerializationFailedException("unable to deserialize [" + className + "]. Class not found.", e); } catch (IOException e) { throw new SerializationFailedException("unable to deserialize [" + className + "]", e); } } }

Target:
private Object deserializePayload(byte[] bytes, MimeType contentType) { if (TEXT_PLAIN.equals(contentType)) { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new SerializationFailedException("unable to deserialize [java.lang.String]. Encoding not supported.", e); } } else { String className = JavaClassMimeTypeConversion.classNameFromMimeType(contentType); try { Class<?> targetType = this.payloadTypeCache.get(className); if (targetType == null) { targetType = ClassUtils.forName(className, null); this.payloadTypeCache.put(className, targetType); } return this.codec.decode(bytes, targetType); } catch (ClassNotFoundException e) { throw new SerializationFailedException("unable to deserialize [" + className + "]. Class not found.", e); } catch (IOException e) { throw new SerializationFailedException("unable to deserialize [" + className + "]", e); } } }
Source:
protected List<String> run(Map<String, Object> params) throws LiteCoreException { List<String> docIDs = new ArrayList<>(); C4QueryOptions opts = new C4QueryOptions(); AllocSlice encodedParams = encodeParameters(params); C4QueryEnumerator e = query.run(opts, encodedParams); assertNotNull(e); while (e.next()) { docIDs.add(e.getColumns().getValueAt(0).asString()); } if (e != null) e.free(); if (encodedParams != null) encodedParams.free(); return docIDs; }

Target:
protected List<String> run(Map<String, Object> params) throws LiteCoreException { List<String> docIDs = new ArrayList<>(); C4QueryOptions opts = new C4QueryOptions(); AllocSlice encodedParams = encodeParameters(params); C4QueryEnumerator e = query.run(opts, encodedParams); try { assertNotNull(e); while (e.next()) { docIDs.add(e.getColumns().getValueAt(0).asString()); } return docIDs; } finally { if (e != null) e.free(); if (encodedParams != null) encodedParams.free(); } }
Source:
public KeyValue<String, String> next() { String pair = pairIter.next(); Iterator<String> keyValIter = Splitter.on(keyValDelimiter).trimResults().split(pair).iterator(); String key = keyValIter.next(); if (!keyValIter.hasNext()) { throw new IllegalArgumentException(String.format("Invalid syntax for key-value pair in list: %s. " + "%s is expected to to be a string separated " + "by one and only one %s", pair, pair, keyValDelimiter)); } String val = keyValIter.next(); if (keyValIter.hasNext()) { throw new IllegalArgumentException(String.format("Invalid syntax for key-value pair in list: %s. " + "%s is expected to to be a string separated " + "by one and only one %s", pair, pair, keyValDelimiter)); } return new KeyValue<>(key, val); }

Target:
public KeyValue<String, String> next() { String pair = pairIter.next(); Iterator<String> keyValIter = Splitter.on(keyValDelimiter).trimResults().split(pair).iterator(); String key = keyValIter.next(); if (!keyValIter.hasNext()) { throw new IllegalArgumentException(String.format("Invalid syntax for key-value pair in list: %s. " + "It is expected to be a string separated " + "by exactly one %s", pair, keyValDelimiter)); } String val = keyValIter.next(); if (keyValIter.hasNext()) { throw new IllegalArgumentException(String.format("Invalid syntax for key-value pair in list: %s. " + "It is expected to be a string separated " + "by exactly one %s", pair, keyValDelimiter)); } return new KeyValue<>(key, val); }
Source:
public void testToString() { assertEquals( ENTITY_DIMENSION.toString(), "EntityDimension[name='country', longName='country', description='country', dimensionType=ENTITY, dataType=Country, cardinality=SMALL, friendlyName='name']" ); assertEquals( DEGENERATE_DIMENSION.toString(), "DegenerateDimension[columnType=FIELD, name='overallRating', longName='overallRating', description='overallRating', dimensionType=DEGENERATE, dataType=String, cardinality=SMALL, friendlyName='overallRating']" ); assertEquals( TIME_DIMENSION.toString(), "TimeDimension[timeZone=Pacific Standard Time, timeGrain=DAY, columnType=TEMPORAL, name='recordedTime', longName='recordedTime', description='recordedTime', dimensionType=DEGENERATE, dataType=class java.lang.Long, cardinality=LARGE, friendlyName='recordedTime']" ); }

Target:
public void testToString() { assertEquals( "EntityDimension[name='country', longName='country', description='country', dimensionType=ENTITY, dataType=Country, cardinality=SMALL, friendlyName='name']", ENTITY_DIMENSION.toString() ); assertEquals( "DegenerateDimension[columnType=FIELD, name='overallRating', longName='overallRating', description='overallRating', dimensionType=DEGENERATE, dataType=String, cardinality=SMALL, friendlyName='overallRating']", DEGENERATE_DIMENSION.toString() ); assertEquals( "TimeDimension[timeZone=Pacific Standard Time, timeGrain=DAY, columnType=TEMPORAL, name='recordedTime', longName='recordedTime', description='recordedTime', dimensionType=DEGENERATE, dataType=class java.lang.Long, cardinality=LARGE, friendlyName='recordedTime']", TIME_DIMENSION.toString() ); }
Source:
public void testRpad() { String rpad = StringUtils.rpad("abc", 7, "de"); Assert.assertEquals("abcdede", rpad); rpad = StringUtils.rpad("abc", 6, "de"); Assert.assertEquals("abcded", rpad); rpad = StringUtils.rpad("abc", 2, "de"); Assert.assertEquals("ab", rpad); rpad = StringUtils.rpad("abc", 0, "de"); Assert.assertEquals("", rpad); rpad = StringUtils.rpad("abc", -1, "de"); Assert.assertNull(rpad); rpad = StringUtils.lpad("abc", 10, ""); Assert.assertNull(rpad); rpad = StringUtils.lpad("abc", 1, ""); Assert.assertNull(rpad); }

Target:
public void testRpad() { String rpad = StringUtils.rpad("abc", 7, "de"); Assert.assertEquals("abcdede", rpad); rpad = StringUtils.rpad("abc", 6, "de"); Assert.assertEquals("abcded", rpad); rpad = StringUtils.rpad("abc", 2, "de"); Assert.assertEquals("ab", rpad); rpad = StringUtils.rpad("abc", 0, "de"); Assert.assertEquals("", rpad); rpad = StringUtils.rpad("abc", -1, "de"); Assert.assertEquals("", rpad); rpad = StringUtils.rpad("abc", 10, ""); Assert.assertEquals("abc", rpad); rpad = StringUtils.rpad("abc", 1, ""); Assert.assertEquals("a", rpad); }
Source:
static File copyTestFile(String file) throws IOException { File newFile = File.createTempFile(file, "test"); InputStream in = QueueTestUtils.class.getResourceAsStream(file); BufferedSink sink = Okio.buffer(Okio.sink(newFile)); sink.writeAll(Okio.source(in)); sink.flush(); sink.close(); assertTrue(newFile.exists()); return newFile; }

Target:
static File copyTestFile(String file) throws IOException { File newFile = File.createTempFile(file, "test"); InputStream in = QueueTestUtils.class.getResourceAsStream(file); try (BufferedSink sink = Okio.buffer(Okio.sink(newFile))) { sink.writeAll(Okio.source(in)); } assertTrue(newFile.exists()); return newFile; }
Source:
public void testStreamInputPacketIndexInvalidAppend() { fFixture = new StreamInputPacketIndex(); assertTrue(fFixture.append(new PacketStub(0, 0, 1))); assertFalse("Same offset", fFixture.append(new PacketStub(0, 1, 2))); assertFalse("Before", fFixture.append(new PacketStub(1, -1, 0))); assertFalse("Empty", fFixture.append(new PacketStub(1, -1, 0) { @Override public long getContentSizeBits() { return 0; } @Override public long getPayloadStartBits() { return 0; } })); }

Target:
public void testStreamInputPacketIndexInvalidAppend() { fFixture = new StreamInputPacketIndex(); assertTrue(fFixture.append(new PacketStub(0, 0, 1))); assertFalse("Same offset", fFixture.append(new PacketStub(0, 1, 2))); assertFalse("Before", fFixture.append(new PacketStub(1, -1, 0))); assertFalse("Empty", fFixture.append(new PacketStub(2, 3, 4) { @Override public long getContentSizeBits() { return 0; } @Override public long getPayloadStartBits() { return 0; } })); }
Source:
public String toString() { return "SimpleMethodInvocation [method=" + method + "]"; }

Target:
public String toString() { return "SimpleMethodInvocation [method=" + method + ']'; }
Source:
private void recycleTransactionalProducer(FlinkKafkaInternalProducer<byte[], byte[]> producer) { availableTransactionalIds.add(producer.getTransactionalId()); producer.close(Duration.ofSeconds(0)); }

Target:
private void recycleTransactionalProducer(FlinkKafkaInternalProducer<byte[], byte[]> producer) { availableTransactionalIds.add(producer.getTransactionalId()); producer.flush(); producer.close(Duration.ofSeconds(0)); }
Source:
public final String toString() { StackTraceElement element = new StackTraceElement(getClassName(), getMethodName(), getFileName().orElse(null), getLineNumber()); return element.toString(); }

Target:
public final String toString() { StackTraceElement element = new StackTraceElement( getClassName().orElse("UnknownClass"), getMethodName().orElse("UnknownMethod"), getFileName().orElse(null), getLineNumber().orElse(0)); return element.toString(); }
Source:
public void getProblemFacts() { TestdataAbstractSolutionBasedSolution solution = new TestdataAbstractSolutionBasedSolution(); TestdataValue singleValue = new TestdataValue("sv1"); solution.setSingleValue(singleValue); TestdataValue v1 = new TestdataValue("v1"); TestdataValue v2 = new TestdataValue("v2"); TestdataValue v3 = new TestdataValue("v3"); List<TestdataValue> valueList = Arrays.asList(v1, v2, v3); solution.setValueList(valueList); List<TestdataEntity> entityList = Arrays.asList( new TestdataEntity("e1"), new TestdataEntity("e2"), new TestdataEntity("e3")); solution.setEntityList(entityList); TestdataEntity singleEntity = new TestdataEntity("se1"); solution.setSingleEntity(singleEntity); SimpleScore score = SimpleScore.of(-10); solution.setScore(score); assertThat((Collection<Object>) solution.getProblemFactList()).containsExactly(singleValue, v1, v2, v3); }

Target:
public void getProblemFacts() { TestdataAbstractSolutionBasedSolution solution = new TestdataAbstractSolutionBasedSolution(); TestdataValue singleValue = new TestdataValue("sv1"); solution.setSingleValue(singleValue); TestdataValue v1 = new TestdataValue("v1"); TestdataValue v2 = new TestdataValue("v2"); TestdataValue v3 = new TestdataValue("v3"); List<TestdataValue> valueList = Arrays.asList(v1, v2, v3); solution.setValueList(valueList); List<TestdataEntity> entityList = Arrays.asList( new TestdataEntity("e1"), new TestdataEntity("e2"), new TestdataEntity("e3")); solution.setEntityList(entityList); TestdataEntity singleEntity = new TestdataEntity("se1"); solution.setSingleEntity(singleEntity); SimpleScore score = SimpleScore.of(-10); solution.setScore(score); assertThat(solution.getProblemFactList()).containsExactly(singleValue, v1, v2, v3); }
Source:
private void validateNewAssignment(Map<String, List<DatastreamTask>> newAssignmentsByInstance) { if (_config.getMaxDatastreamTasksPerInstance() > 0) { Map<String, Integer> instancesWithTaskCountAboveThreshold = newAssignmentsByInstance.entrySet().stream() .filter(e -> !e.getKey().equals(PAUSED_INSTANCE) && (e.getValue().size() > _config.getMaxDatastreamTasksPerInstance())) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().size())); if (instancesWithTaskCountAboveThreshold.size() > 0) { throw new DatastreamRuntimeException(String.format("Too many tasks assigned to some instances, max tasks per " + "instance: %d, instances above the threshold: %s", _config.getMaxDatastreamTasksPerInstance(), instancesWithTaskCountAboveThreshold)); } } }

Target:
void validateNewAssignment(Map<String, List<DatastreamTask>> newAssignmentsByInstance) { if (_config.getMaxDatastreamTasksPerInstance() > 0) { Map<String, Integer> instancesWithTaskCountAboveThreshold = newAssignmentsByInstance.entrySet().stream() .filter(e -> !e.getKey().equals(PAUSED_INSTANCE) && (e.getValue().size() > _config.getMaxDatastreamTasksPerInstance())) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().size())); if (instancesWithTaskCountAboveThreshold.size() > 0) { throw new DatastreamRuntimeException(String.format("Too many tasks assigned to some instances, max tasks per " + "instance: %d, instances above the threshold: %s", _config.getMaxDatastreamTasksPerInstance(), instancesWithTaskCountAboveThreshold)); } } }
Source:
public CappedHaplotypeProbabilities(final HaplotypeProbabilities haplotypeProbabilities, double cap) { super(haplotypeProbabilities.getHaplotype()); this.cap = cap; final double[] logLikelihoods = haplotypeProbabilities.getLogLikelihoods(); final double max = MathUtil.max(logLikelihoods); final double[] cappedLogLikelihoods = MathUtil.sum(logLikelihoods,-max); this.setLogLikelihoods(MathUtil.max(cappedLogLikelihoods,cap)); }

Target:
public CappedHaplotypeProbabilities(final HaplotypeProbabilities haplotypeProbabilities, double cap) { super(haplotypeProbabilities.getHaplotype()); this.cap = cap; final double[] logLikelihoods = haplotypeProbabilities.getLogLikelihoods(); final double[] cappedLogLikelihoods = MathUtil.subtractMax(logLikelihoods); this.setLogLikelihoods(MathUtil.capFromBelow(cappedLogLikelihoods, cap)); }
Source:
@Test public void successWithHeaders() { Object body = new Object(); Response<Object> response = Response.success(body, Headers.of("foo", "bar")); assertThat(response.raw()).isNotNull(); assertThat(response.code()).isEqualTo(200); assertThat(response.message()).isEqualTo("OK"); assertThat(response.headers().size()).isEqualTo(1); assertThat(response.headers().get("foo")).isEqualTo("bar"); assertThat(response.isSuccess()).isTrue(); assertThat(response.body()).isSameAs(body); assertThat(response.errorBody()).isNull(); }

Target:
@Test public void successWithHeaders() { Object body = new Object(); Headers headers = Headers.of("foo", "bar"); Response<Object> response = Response.success(body, headers); assertThat(response.raw()).isNotNull(); assertThat(response.code()).isEqualTo(200); assertThat(response.message()).isEqualTo("OK"); assertThat(response.headers().size()).isEqualTo(1); assertThat(response.headers().get("foo")).isSameAs("bar"); assertThat(response.isSuccess()).isTrue(); assertThat(response.body()).isSameAs(body); assertThat(response.errorBody()).isNull(); }
Source:
ClientConnectionManager newClientConnectionManager(HttpParams params, X509HostnameVerifier verifier, SSLContext context, Closer closer) throws NoSuchAlgorithmException, KeyManagementException { SchemeRegistry schemeRegistry = new SchemeRegistry(); Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); SSLSocketFactory sf = new SSLSocketFactory(context); sf.setHostnameVerifier(verifier); Scheme https = new Scheme("https", sf, 443); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", sf, 443)); final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); closer.addToClose(new Closeable() { @Override public void close() throws IOException { cm.shutdown(); } }); return cm; }

Target:
ClientConnectionManager newClientConnectionManager(HttpParams params, X509HostnameVerifier verifier, SSLContext context, Closer closer) throws NoSuchAlgorithmException, KeyManagementException { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sf = new SSLSocketFactory(context); sf.setHostnameVerifier(verifier); schemeRegistry.register(new Scheme("https", sf, 443)); final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); closer.addToClose(new Closeable() { @Override public void close() throws IOException { cm.shutdown(); } }); return cm; }
Source:
boolean removeKeysById(int grpId, Set<Integer> ids) { return removeKeysById(grpKeys.get(grpId), ids); }

Target:
boolean removeKeysById(int grpId, Set<Integer> ids) { List<GroupKey> keys = grpKeys.get(grpId); if (F.isEmpty(keys)) return false; return keys.subList(1, keys.size()).removeIf(key -> ids.contains(key.unsignedId())); }
Source:
public long getTimeTillUpdate(long currMediaTime) { long next = super.getTimeTillUpdate(currMediaTime); if (monitorThread == null) return next; if (next == sage.Sage.MILLIS_PER_WEEK) { inDemand = currMediaTime; synchronized (srtLock) { if (inDemand != -1) { loadSubtitlesFromFiles(); } next = super.getTimeTillUpdate(currMediaTime); } if (next == sage.Sage.MILLIS_PER_WEEK) { next = 1000; subEntryPos = -1; } } return next; }

Target:
public long getTimeTillUpdate(long currMediaTime) { long next = super.getTimeTillUpdate(currMediaTime); if (monitorThread == null) return next; if (next == NO_MORE_SUBS_LONG_WAIT) { inDemand = currMediaTime; synchronized (srtLock) { if (inDemand != -1) { loadSubtitlesFromFiles(); } next = super.getTimeTillUpdate(currMediaTime); } if (next == NO_MORE_SUBS_LONG_WAIT) { next = 1000; subEntryPos = -1; } } return next; }
Source:
public Response execute(Command command) throws WebDriverException { if (DriverCommand.NEW_SESSION.equals(command.getName())) { serviceOptional.ifPresent(driverService -> { try { driverService.start(); } catch (IOException e) { throw new WebDriverException(e.getMessage(), e); } }); } Response response; try { for (IDriverCommandListener listener : listeners) { listener.beforeEvent(command); } if (command.getName().equals("newSession")) { LOGGER.info("New session request. Parameters: ".concat(command.getParameters().toString())); } response = super.execute(command); for (IDriverCommandListener listener : listeners) { listener.afterEvent(command); } } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); if (rootCause instanceof ConnectException && rootCause.getMessage().contains("Connection refused")) { throw serviceOptional.map(service -> { if (service.isRunning()) { return new WebDriverException("The session is closed!", rootCause); } return new WebDriverException("The appium server has accidentally died!", rootCause); }).orElseGet((Supplier<WebDriverException>) () -> new WebDriverException(rootCause.getMessage(), rootCause)); } throw new WebDriverException(t); } finally { if (DriverCommand.QUIT.equals(command.getName())) { serviceOptional.ifPresent(DriverService::stop); } } if (DriverCommand.NEW_SESSION.equals(command.getName()) && getCommandCodec() instanceof W3CHttpCommandCodec) { setCommandCodec(new AppiumW3CHttpCommandCodec()); getAdditionalCommands().forEach(this::defineCommand); } return response; }

Target:
public Response execute(Command command) throws WebDriverException { if (DriverCommand.NEW_SESSION.equals(command.getName())) { serviceOptional.ifPresent(driverService -> { try { driverService.start(); } catch (IOException e) { throw new WebDriverException(e.getMessage(), e); } }); } Response response; try { for (IDriverCommandListener listener : listeners) { listener.beforeEvent(command); } response = super.execute(command); for (IDriverCommandListener listener : listeners) { listener.afterEvent(command); } } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); if (rootCause instanceof ConnectException && rootCause.getMessage().contains("Connection refused")) { throw serviceOptional.map(service -> { if (service.isRunning()) { return new WebDriverException("The session is closed!", rootCause); } return new WebDriverException("The appium server has accidentally died!", rootCause); }).orElseGet((Supplier<WebDriverException>) () -> new WebDriverException(rootCause.getMessage(), rootCause)); } throw new WebDriverException(t); } finally { if (DriverCommand.QUIT.equals(command.getName())) { serviceOptional.ifPresent(DriverService::stop); } } if (DriverCommand.NEW_SESSION.equals(command.getName()) && getCommandCodec() instanceof W3CHttpCommandCodec) { setCommandCodec(new AppiumW3CHttpCommandCodec()); getAdditionalCommands().forEach(this::defineCommand); } return response; }
Source:
public void setReportTitle(String reportTitle) { this.reportTitle = reportTitle; this.directoryQualifier = reportTitle.replaceAll("[^A-Za-z0-9@+-_.,~]", "_"); }

Target:
public void setReportTitle(String reportTitle) { this.reportTitle = StringUtils.isEmpty(reportTitle) ? "" : reportTitle.trim(); }
Source:
private void releaseCurrentSortBuffer() { if (currentSortBuffer != null) { currentSortBuffer.release(); currentSortBuffer = null; } }

Target:
private void releaseCurrentSortBuffer() { if (currentSortBuffer != null) { currentSortBuffer.release(); } }
Source:
public void testInstanceIdIsSet() throws Exception { final CountDownLatch latch = new CountDownLatch(1); ThreadSpyAuditWrapper wrapper = new ThreadSpyAuditWrapper( latch ); String expected = UUID.randomUUID().toString(); PentahoAsyncReportExecution execution = new PentahoAsyncReportExecution( url, component, handler, session, expected, wrapper ); PentahoAsyncExecutor executor = new PentahoAsyncExecutor( 2 ); executor.addTask( execution, session ); latch.await( 10, TimeUnit.DAYS ); assertEquals( expected, wrapper.capturedId ); }

Target:
public void testInstanceIdIsSet() throws Exception { final CountDownLatch latch = new CountDownLatch(1); ThreadSpyAuditWrapper wrapper = new ThreadSpyAuditWrapper( latch ); String expected = UUID.randomUUID().toString(); PentahoAsyncReportExecution execution = new PentahoAsyncReportExecution( url, component, handler, session, expected, wrapper ); PentahoAsyncExecutor executor = new PentahoAsyncExecutor( 2 ); executor.addTask( execution, session ); latch.await( 10, TimeUnit.SECONDS ); assertEquals( expected, wrapper.capturedId ); }