auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static NotificationTag create(DownloadBatch batch, String packageName) { if (batch.isQueuedForWifi()) { return new NotificationTag(DownloadNotifier.TYPE_WAITING, packageName); } else if (batch.isRunning() && batch.shouldShowActiveItem()) { return new NotificationTag(DownloadNotifier.TYPE_ACTIVE, packageName); } else if (batch.isError() && !batch.isCancelled() && batch.shouldShowCompletedItem()) { return new NotificationTag(DownloadNotifier.TYPE_FAILED, String.valueOf(batch.getBatchId())); } else if (batch.isCancelled() && batch.shouldShowCompletedItem()) { return new NotificationTag(DownloadNotifier.TYPE_CANCELLED, String.valueOf(batch.getBatchId())); } else if (batch.isSuccess() && batch.shouldShowCompletedItem()) { return new NotificationTag(DownloadNotifier.TYPE_SUCCESS, String.valueOf(batch.getBatchId())); } else { return null; } }

Target:
static NotificationTag create(DownloadBatch batch, String packageName) { if (batch.isQueuedForWifi()) { return new NotificationTag(SynchronisedDownloadNotifier.TYPE_WAITING, packageName); } else if (batch.isRunning() && batch.shouldShowActiveItem()) { return new NotificationTag(SynchronisedDownloadNotifier.TYPE_ACTIVE, packageName); } else if (batch.isError() && !batch.isCancelled() && batch.shouldShowCompletedItem()) { return new NotificationTag(SynchronisedDownloadNotifier.TYPE_FAILED, String.valueOf(batch.getBatchId())); } else if (batch.isCancelled() && batch.shouldShowCompletedItem()) { return new NotificationTag(SynchronisedDownloadNotifier.TYPE_CANCELLED, String.valueOf(batch.getBatchId())); } else if (batch.isSuccess() && batch.shouldShowCompletedItem()) { return new NotificationTag(SynchronisedDownloadNotifier.TYPE_SUCCESS, String.valueOf(batch.getBatchId())); } else { return null; } }
Source:
public synchronized Optional<List<String>> getPartitionNames(String databaseName, String tableName) { return doGetPartitionNames(databaseName, tableName, null); }

Target:
public synchronized Optional<List<String>> getPartitionNames(String databaseName, String tableName) { return doGetPartitionNames(databaseName, tableName, ImmutableMap.of()); }
Source:
private Set<Type> interfacesWithSubstitution(Symbol.TypeSymbol symbol, TypeSubstitution substitution) { return symbol.interfaces().stream() .map(interfaceType -> applySubstitution(interfaceType, substitution)) .flatMap(substitutedInterfaceType -> supertypes(substitutedInterfaceType).stream()) .collect(Collectors.toSet()); }

Target:
private Set<Type> interfacesWithSubstitution(Symbol.TypeSymbol symbol, TypeSubstitution substitution) { return symbol.interfaces().stream() .flatMap(interfaceType -> supertypes(applySubstitution(interfaceType, substitution)).stream()) .collect(Collectors.toSet()); }
Source:
public void testLoadFailure() throws Exception { SyncRequestProcessor.setSnapCount(50); ZooKeeper zk = createZKClient(hostPort); try { for (int i = 0; i< NUM_MESSAGES; i++) { zk.create("/data-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); } } finally { zk.close(); } stopServer(); File logDir = new File(tmpDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION); File[] logFiles = FileTxnLog.getLogFiles(logDir.listFiles(), 0); Assert.assertTrue(logFiles.length > 4); Assert.assertTrue("delete the first log file", logFiles[0].delete()); long secondStartZxid = Util.getZxidFromName(logFiles[1].getName(), "log"); FileTxnLog txnLog = new FileTxnLog(logDir); TxnIterator itr = txnLog.read(1, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); itr = txnLog.read(secondStartZxid, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); Assert.assertTrue(itr.next()); long nextZxid = itr.getHeader().getZxid(); itr = txnLog.read(nextZxid, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); long thirdStartZxid = Util.getZxidFromName(logFiles[2].getName(), "log"); itr = txnLog.read(thirdStartZxid, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); Assert.assertTrue(itr.next()); nextZxid = itr.getHeader().getZxid(); itr = txnLog.read(nextZxid, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); }

Target:
public void testLoadFailure() throws Exception { ZooKeeper zk = createZKClient(hostPort); try { for (int i = 0; i< NUM_MESSAGES; i++) { zk.create("/data-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); } } finally { zk.close(); } stopServer(); File logDir = new File(tmpDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION); File[] logFiles = FileTxnLog.getLogFiles(logDir.listFiles(), 0); Assert.assertTrue(logFiles.length > NUM_MESSAGES / 100); Assert.assertTrue("delete the first log file", logFiles[0].delete()); long secondStartZxid = Util.getZxidFromName(logFiles[1].getName(), "log"); FileTxnLog txnLog = new FileTxnLog(logDir); TxnIterator itr = txnLog.read(1, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); itr = txnLog.read(secondStartZxid, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); Assert.assertTrue(itr.next()); long nextZxid = itr.getHeader().getZxid(); itr = txnLog.read(nextZxid, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); long thirdStartZxid = Util.getZxidFromName(logFiles[2].getName(), "log"); itr = txnLog.read(thirdStartZxid, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); Assert.assertTrue(itr.next()); nextZxid = itr.getHeader().getZxid(); itr = txnLog.read(nextZxid, false); Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid()); }
Source:
void onInsertChunkD3() { onInsertChunk("```{d3}\n\n```\n", 1, 0); }

Target:
void onInsertChunkD3() { if (notebook_ != null) { Scope setupScope = notebook_.getSetupChunkScope(); if (setupScope == null) { onInsertChunk("```{r setup}\nlibrary(r2d3)\n```\n\n```{d3 data=}\n\n```\n", 4, 12); } else { onInsertChunk("```{d3 data=}\n\n```\n", 0, 12); } } }
Source:
private Set<ConstraintViolation<?>> validate(final String typeName, final String propertyName, final JsonElement propertyElement) { Assert.requireNonNull(propertyElement, "propertyElement"); if (!propertyElement.isJsonPrimitive() && !propertyElement.isJsonNull()) { throw new IllegalArgumentException("Only primitive or null properties supported. Wrong type for " + typeName + "." + propertyName); } if (propertyElement.isJsonNull()) { return remoteValidator.validateValue(typeName, propertyName, null); } JsonPrimitive primitiveValue = propertyElement.getAsJsonPrimitive(); if (primitiveValue.isBoolean()) { return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsBoolean()); } else if (primitiveValue.isNumber()) { return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsNumber()); } else if (primitiveValue.isString()) { return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsString()); } throw new IllegalArgumentException("Not supported type for " + typeName + "." + propertyName); }

Target:
private Set<ConstraintViolation<?>> validate(final String typeName, final String propertyName, final JsonElement propertyElement) { Assert.requireNonNull(propertyElement, "propertyElement"); if (!propertyElement.isJsonPrimitive() && !propertyElement.isJsonNull()) { throw new IllegalArgumentException("Only primitive or null properties supported. Wrong type for " + typeName + "." + propertyName); } if (propertyElement.isJsonNull()) { return remoteValidator.validateValue(typeName, propertyName, null); } final JsonPrimitive primitiveValue = propertyElement.getAsJsonPrimitive(); if (primitiveValue.isBoolean()) { return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsBoolean()); } else if (primitiveValue.isNumber()) { return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsNumber()); } else if (primitiveValue.isString()) { return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsString()); } throw new IllegalArgumentException("Not supported type for " + typeName + "." + propertyName); }
Source:
private SignedJWTInfo getSignedJwtInfo(String accessToken) throws ParseException { String signature = accessToken.split("\\.")[2]; SignedJWTInfo signedJWTInfo = new SignedJWTInfo(); Cache gatewaySignedJWTParseCache = CacheProvider.getGatewaySignedJWTParseCache(); if (gatewaySignedJWTParseCache != null) { Object cachedEntry = gatewaySignedJWTParseCache.get(signature); if (cachedEntry != null) { signedJWTInfo = (SignedJWTInfo) cachedEntry; } else { SignedJWT signedJWT = SignedJWT.parse(accessToken); signedJWTInfo.setSignedJWT(signedJWT); signedJWTInfo.setJwtClaimsSet(signedJWT.getJWTClaimsSet()); signedJWTInfo.setToken(accessToken); gatewaySignedJWTParseCache.put(signature, signedJWTInfo); } } else { SignedJWT signedJWT = SignedJWT.parse(accessToken); signedJWTInfo.setSignedJWT(signedJWT); signedJWTInfo.setJwtClaimsSet(signedJWT.getJWTClaimsSet()); signedJWTInfo.setToken(accessToken); } return signedJWTInfo; }

Target:
private SignedJWTInfo getSignedJwtInfo(String accessToken) throws ParseException { String signature = accessToken.split("\\.")[2]; SignedJWTInfo signedJWTInfo; Cache gatewaySignedJWTParseCache = CacheProvider.getGatewaySignedJWTParseCache(); if (gatewaySignedJWTParseCache != null) { Object cachedEntry = gatewaySignedJWTParseCache.get(signature); if (cachedEntry != null) { signedJWTInfo = (SignedJWTInfo) cachedEntry; } else { SignedJWT signedJWT = SignedJWT.parse(accessToken); JWTClaimsSet jwtClaimsSet = signedJWT.getJWTClaimsSet(); signedJWTInfo = new SignedJWTInfo(accessToken, signedJWT, jwtClaimsSet); gatewaySignedJWTParseCache.put(signature, signedJWTInfo); } } else { SignedJWT signedJWT = SignedJWT.parse(accessToken); JWTClaimsSet jwtClaimsSet = signedJWT.getJWTClaimsSet(); signedJWTInfo = new SignedJWTInfo(accessToken, signedJWT, jwtClaimsSet); } return signedJWTInfo; }
Source:
public static Predicate<Command> wereAfter(final Timestamp from) { return new Predicate<Command>() { @Override public boolean apply(@Nullable Command request) { checkNotNull(request); final Timestamp timestamp = getTimestamp(request); return Timestamps.isLater(timestamp, from); } }; }

Target:
public static Predicate<Command> wereAfter(final Timestamp from) { return new Predicate<Command>() { @Override public boolean apply(@Nullable Command request) { checkNotNull(request); final Timestamp timestamp = getTimestamp(request); return Timestamps.isLaterThan(timestamp, from); } }; }
Source:
private double getHeightAt(BufferedImage image, int x, int y) { int rgb = image.getRGB(x, y); int red = rgb >>> 16 & 0xFF; int green = rgb >>> 8 & 0xFF; int blue = rgb & 0xFF; if (red == 0 && green == 0 && blue == 0) { return 0; } double scale = (red + blue + green) / 3D / 255D; return scale * intensity; }

Target:
private double getHeightAt(BufferedImage image, int x, int y) { int rgb = image.getRGB(x, y); if (rgb == 0) { return 0; } int red = rgb >>> 16 & 0xFF; int green = rgb >>> 8 & 0xFF; int blue = rgb & 0xFF; double scale = (red + blue + green) / 3D / 255D; return scale * intensity; }
Source:
public DroolsFilterUniConstraintStream(DroolsConstraintFactory<Solution_> constraintFactory, DroolsAbstractUniConstraintStream<Solution_, A> parent, Predicate<A> predicate) { super(constraintFactory, parent.getAnchor().filter(predicate)); this.parent = parent; }

Target:
public DroolsFilterUniConstraintStream(DroolsConstraintFactory<Solution_> constraintFactory, DroolsAbstractUniConstraintStream<Solution_, A> parent, Predicate<A> predicate) { super(constraintFactory); this.parent = parent; this.predicate = predicate; }
Source:
public File getOutputFileToWrite(Obs obs) throws IOException { String title = obs.getComplexData().getTitle(); String extension = FilenameUtils.getExtension(title); File dir = OpenmrsUtil.getDirectoryInApplicationDataDirectory(Context.getAdministrationService().getGlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_COMPLEX_OBS_DIR)); File outputfile = null; String uuid = obs.getUuid(); if (null == title) { String now = longfmt.format(new Date()); outputfile = new File(dir, now + '_' + uuid); } else { if (!(extension.equals(""))) { extension = "." + extension; } String titleWithoutExtension = title.replace(extension, ""); outputfile = new File(dir, titleWithoutExtension + '_' + uuid + extension); } return outputfile; }

Target:
public File getOutputFileToWrite(Obs obs) throws IOException { String title = obs.getComplexData().getTitle(); String titleWithoutExtension = FilenameUtils.removeExtension(title); String extension = "." + StringUtils.defaultIfEmpty(FilenameUtils.getExtension(title), "dat"); String uuid = obs.getUuid(); String filename; if (StringUtils.isNotBlank(titleWithoutExtension)) { filename = titleWithoutExtension + "_" + uuid + extension; } else { filename = uuid + extension; } File dir = OpenmrsUtil.getDirectoryInApplicationDataDirectory( Context.getAdministrationService().getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_COMPLEX_OBS_DIR)); File outputfile = new File(dir, filename); return outputfile; }
Source:
public Object[] getFiniteSupport() { checkHasParams(); return null; }

Target:
public Object[] getFiniteSupport() { if (finiteSupport == null) { checkHasParams(); int supportSize = 0; while (!Util.closeToZero(getProb(supportSize))) supportSize++; finiteSupport = new Object[supportSize]; for (int i = 0; i < supportSize; i++) finiteSupport[i] = i; } return finiteSupport; }
Source:
public @NotNull Builder setTransportHeaders(Map<String, String> transportHeaders) { if (transportHeaders == null) { throw new NullPointerException("`transportHeaders` cannot be null"); } this.transportHeaders = transportHeaders; return this; }

Target:
public @NotNull Builder setTransportHeaders(Map<String, String> transportHeaders) { this.transportHeaders = transportHeaders; return this; }
Source:
public ServiceAccount store(String token, InputStream service) throws IOException { final Path path = rootLocation.resolve(token + JSON_EXTENSION); ServiceAccount object = jsonSerialise.deserialiseQuietly(service, path); jsonSerialise.serialise(path, object); return object; }

Target:
public ServiceAccount store(String token, InputStream service) throws IOException { final Path path = rootLocation.resolve(token + JSON_EXTENSION); if (!Files.exists(path)) { ServiceAccount object = jsonSerialise.deserialiseQuietly(service, path); jsonSerialise.serialise(path, object); return object; } throw new FileAlreadyExistsException("The service token already exists : " + path); }
Source:
public Collection<Permission> getAllPermissions() { Collection<Permission> result = new ArrayList<Permission>(permissions); for (Role role : nestedRoles) { if (role == this) { throw new IllegalStateException("cyclic dependency detected"); } result.addAll(role.getAllPermissions()); } return result; }

Target:
public Collection<Permission> getAllPermissions() { Collection<Permission> result = new ArrayList<Permission>(permissions); for (Role role : nestedRoles) { if (role == this) { LOGGER.warn("cyclic dependency detected"); return Collections.emptyList(); } result.addAll(role.getAllPermissions()); } return result; }
Source:
public BukkitBlockCommandSender(WorldEditPlugin plugin, BlockCommandSender sender) { checkNotNull(plugin); checkNotNull(sender); this.plugin = plugin; this.sender = sender; this.location = BukkitAdapter.adapt(sender.getBlock().getLocation()); this.uuid = new UUID("COMMAND_BLOCK".hashCode(), sender.getName().hashCode()); }

Target:
public BukkitBlockCommandSender(WorldEditPlugin plugin, BlockCommandSender sender) { checkNotNull(plugin); checkNotNull(sender); this.plugin = plugin; this.sender = sender; this.location = BukkitAdapter.adapt(sender.getBlock().getLocation()); this.uuid = UUID.nameUUIDFromBytes((UUID_PREFIX + sender.getName()).getBytes(StandardCharsets.UTF_8)); }
Source:
private void checkVdsMemoryThresholdPercentage(Cluster cluster, VdsStatistics stat) { Integer maxUsedPercentageThreshold = cluster.getLogMaxMemoryUsedThreshold(); if (stat.getUsageMemPercent() > maxUsedPercentageThreshold) { logMemoryAuditLog(vds, stat, AuditLogType.VDS_HIGH_MEM_USE, maxUsedPercentageThreshold); } }

Target:
private void checkVdsMemoryThresholdPercentage(Cluster cluster, VdsStatistics stat) { Integer maxUsedPercentageThreshold = cluster.getLogMaxMemoryUsedThreshold(); if (stat.getUsageMemPercent() > maxUsedPercentageThreshold) { logMemoryAuditLog(vds, cluster, stat, AuditLogType.VDS_HIGH_MEM_USE, maxUsedPercentageThreshold); } }
Source:
public void whenLightStatsOnActiveSubscriptionThenCorrectRespones() throws IOException { final String et = createEventType().getName(); final Subscription s = createSubscriptionForEventTypeFromBegin(et); publishEvents(et, 15, i -> "{\"foo\":\"bar\"}"); final TestStreamingClient client = TestStreamingClient .create(URL, s.getId(), "max_uncommitted_events=20") .start(); waitFor(() -> assertThat(client.getBatches(), hasSize(15))); final Response response = when().get("/subscriptions?show_status=true").thenReturn(); final ItemsWrapper<Subscription> subsItems = MAPPER.readValue(response.print(), new TypeReference<ItemsWrapper<Subscription>>(){}); for (final Subscription subscription: subsItems.getItems()) { if (subscription.getId().equals(s.getId())) { Assert.assertNotNull(subscription.getStats()); Assert.assertEquals("assigned", subscription.getStats().get(0).getPartitions().get(0).getState()); Assert.assertNotEquals("", subscription.getStats().get(0).getPartitions().get(0).getStreamId()); Assert.assertEquals(SubscriptionEventTypeStats.Partition.AssignmentType.AUTO, subscription.getStats().get(0).getPartitions().get(0).getAssignmentType()); return; } } Assert.assertTrue(false); }

Target:
public void whenLightStatsOnActiveSubscriptionThenCorrectRespones() throws IOException { final String et = createEventType().getName(); final Subscription s = createSubscriptionForEventTypeFromBegin(et); final String owningApplication = s.getOwningApplication(); publishEvents(et, 15, i -> "{\"foo\":\"bar\"}"); final TestStreamingClient client = TestStreamingClient .create(URL, s.getId(), "max_uncommitted_events=20") .start(); waitFor(() -> assertThat(client.getBatches(), hasSize(15))); final Response response = when() .get("/subscriptions?show_status=true&owning_application=" + owningApplication) .thenReturn(); final ItemsWrapper<Subscription> subsItems = MAPPER.readValue(response.print(), new TypeReference<ItemsWrapper<Subscription>>(){}); for (final Subscription subscription: subsItems.getItems()) { if (subscription.getId().equals(s.getId())) { Assert.assertNotNull(subscription.getStatus()); Assert.assertEquals("assigned", subscription.getStatus().get(0).getPartitions().get(0).getState()); Assert.assertEquals(client.getSessionId(), subscription.getStatus().get(0).getPartitions().get(0).getStreamId()); Assert.assertEquals(SubscriptionEventTypeStats.Partition.AssignmentType.AUTO, subscription.getStatus().get(0).getPartitions().get(0).getAssignmentType()); return; } } Assert.assertTrue(false); }
Source:
public boolean isPair(final SAMRecord record) { return record != null && this.getMateAlignmentStart() == record.getAlignmentStart() && record.getMateAlignmentStart() == this.getAlignmentStart() && !NO_ALIGNMENT_REFERENCE_NAME.equals(this.getMateReferenceName()) && !NO_ALIGNMENT_REFERENCE_NAME.equals(record.getMateReferenceName()) && Objects.equals(this.getReferenceName(), record.getMateReferenceName()) && Objects.equals(record.getReferenceName(), this.getMateReferenceName()); }

Target:
public boolean isPair(final SAMRecord record) { return record != null && Objects.equals(this.getReadName(), record.getReadName()) && this.getMateAlignmentStart() == record.getAlignmentStart() && record.getMateAlignmentStart() == this.getAlignmentStart() && !NO_ALIGNMENT_REFERENCE_NAME.equals(this.getMateReferenceName()) && !NO_ALIGNMENT_REFERENCE_NAME.equals(record.getMateReferenceName()) && Objects.equals(this.getReferenceName(), record.getMateReferenceName()) && Objects.equals(record.getReferenceName(), this.getMateReferenceName()); }
Source:
void addCleanupAddon(MApplication app, EModelService modelService) { final String contributionURI = "bundleclass://org.eclipse.e4.ui.workbench.addons.swt/org.eclipse.e4.ui.workbench.addons.cleanupaddon.CleanupAddon"; final String id = "CleanupAddon"; addAddon(app, modelService, contributionURI, id); }

Target:
void addCleanupAddon(MApplication app, EModelService modelService) { final String contributionURI = "bundleclass://org.eclipse.e4.ui.workbench.addons.swt/org.eclipse.e4.ui.workbench.addons.cleanupaddon.CleanupAddon"; final String id = "CleanupAddon"; ProcessorUtil.addAddon(app, modelService, contributionURI, id); }
Source:
void findBySimpleProperty() { Airport vie = null; try { vie = new Airport("airports::vie", "vie", "loww"); airportRepository.save(vie).block(); List<Airport> airports1 = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports1.size()); List<Airport> airports2 = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports2.size()); vie = airportRepository.save(vie).block(); List<Airport> airports = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports.size()); System.out.println("findAllByIata(0): " + airports.get(0)); Airport airport1 = airportRepository.findById(airports.get(0).getId()).block(); assertEquals(airport1.getIata(), vie.getIata()); System.out.println("findById: " + airport1); Airport airport2 = airportRepository.findByIata(airports.get(0).getIata()).block(); assertEquals(airport1.getId(), vie.getId()); System.out.println("findByIata: " + airport2); } finally { airportRepository.delete(vie).block(); } }

Target:
void findBySimpleProperty() { Airport vie = null; try { vie = new Airport("airports::vie", "vie", "loww"); airportRepository.save(vie).block(); List<Airport> airports1 = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports1.size()); List<Airport> airports2 = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports2.size()); vie = airportRepository.save(vie).block(); List<Airport> airports = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports.size()); Airport airport1 = airportRepository.findById(airports.get(0).getId()).block(); assertEquals(airport1.getIata(), vie.getIata()); Airport airport2 = airportRepository.findByIata(airports.get(0).getIata()).block(); assertEquals(airport1.getId(), vie.getId()); } finally { airportRepository.delete(vie).block(); } }
Source:
public void testBinaryStatsWithTruncation() { int defaultTruncLen = ParquetProperties.DEFAULT_STATISTICS_TRUNCATE_LENGTH; int[] validLengths = {1, 2, 16, 64, defaultTruncLen - 1, defaultTruncLen - 1}; for (int len : validLengths) { testBinaryStatsWithTruncation(len); } int[] invalidLengths = {-1, 0, defaultTruncLen + 1}; for (int len : invalidLengths) { try { testBinaryStatsWithTruncation(len); } catch (IllegalArgumentException e) { } } }

Target:
public void testBinaryStatsWithTruncation() { int defaultTruncLen = ParquetProperties.DEFAULT_STATISTICS_TRUNCATE_LENGTH; int[] validLengths = {1, 2, 16, 64, defaultTruncLen - 1}; for (int len : validLengths) { testBinaryStatsWithTruncation(len, 60, 70); testBinaryStatsWithTruncation(len, (int) ParquetMetadataConverter.MAX_STATS_SIZE, 190); testBinaryStatsWithTruncation(len, 280, (int) ParquetMetadataConverter.MAX_STATS_SIZE); testBinaryStatsWithTruncation(len, (int) ParquetMetadataConverter.MAX_STATS_SIZE, (int) ParquetMetadataConverter.MAX_STATS_SIZE); } int[] invalidLengths = {-1, 0, Integer.MAX_VALUE + 1}; for (int len : invalidLengths) { try { testBinaryStatsWithTruncation(len, 80, 20); Assert.fail("Expected IllegalArgumentException but didn't happen"); } catch (IllegalArgumentException e) { } } }
Source:
private double getTotalSizeForDisksWithSnapshots(Collection<DiskImage> diskImages) { return getTotalSizeForDisksByMethod(diskImages, diskImage -> { double sizeForDisk = diskImage.getSize(); if ((storageDomain.getStorageType().isFileDomain() && diskImage.getVolumeType() == VolumeType.Sparse) || diskImage.getVolumeFormat() == VolumeFormat.COW) { if (!VmEntityType.TEMPLATE.equals(diskImage.getVmEntityType())) { sizeForDisk = diskImage.getActualDiskWithSnapshotsSizeInBytes(); } } if (diskImage.getVolumeFormat() == VolumeFormat.COW) { sizeForDisk = Math.ceil(StorageConstants.QCOW_OVERHEAD_FACTOR * sizeForDisk); } return sizeForDisk; }); }

Target:
private double getTotalSizeForDisksWithSnapshots(Collection<DiskImage> diskImages) { return getTotalSizeForDisksByMethod(diskImages, diskImage -> { double sizeForDisk = diskImage.getSize(); if ((storageDomain.getStorageType().isFileDomain() && diskImage.getVolumeType() == VolumeType.Sparse) || diskImage.getVolumeFormat() == VolumeFormat.COW) { sizeForDisk = diskImage.getActualDiskWithSnapshotsSizeInBytes(); } if (diskImage.getVolumeFormat() == VolumeFormat.COW) { sizeForDisk = Math.ceil(StorageConstants.QCOW_OVERHEAD_FACTOR * sizeForDisk); } return sizeForDisk; }); }
Source:
public static boolean isEqualToDefault(EObject object, EStructuralFeature feature) { final Object value = ReferenceUtil.safeEGet(object, feature); final Object defaultValue = feature.getDefaultValue(); if (value == null) { return defaultValue == null; } return value.equals(feature.getDefaultValue()) || "".equals(value); }

Target:
private static boolean isEqualToDefault(EObject object, EStructuralFeature feature) { final Object value = ReferenceUtil.safeEGet(object, feature); final Object defaultValue = feature.getDefaultValue(); if (value == null) { return defaultValue == null; } return value.equals(feature.getDefaultValue()) || "".equals(value); }
Source:
public boolean refresh() throws Exception { prepare(); if (!isOk()) { return false; } repoImpl.refresh(); bridge = new BridgeRepository(repoImpl); for (RepositoryListenerPlugin listener : registry.getPlugins(RepositoryListenerPlugin.class)) { try { listener.repositoryRefreshed(this); } catch (Exception e) { reporter.exception(e, "Updating listener plugin %s", listener); } } return true; }

Target:
public boolean refresh() throws Exception { if (!init()) { return false; } repoImpl.refresh(); bridge = new BridgeRepository(repoImpl); for (RepositoryListenerPlugin listener : registry.getPlugins(RepositoryListenerPlugin.class)) { try { listener.repositoryRefreshed(this); } catch (Exception e) { reporter.exception(e, "Updating listener plugin %s", listener); } } return true; }
Source:
public CoordinatorServerView( ServerInventoryView baseView ) { this.baseView = baseView; this.selectors = Maps.newHashMap(); this.timelines = Maps.newHashMap(); ExecutorService exec = Execs.singleThreaded("OverlordServerView-%s"); baseView.registerSegmentCallback( exec, new ServerView.SegmentCallback() { @Override public ServerView.CallbackAction segmentAdded(DruidServerMetadata server, DataSegment segment) { serverAddedSegment(server, segment); return ServerView.CallbackAction.CONTINUE; } @Override public ServerView.CallbackAction segmentRemoved(final DruidServerMetadata server, DataSegment segment) { serverRemovedSegment(server, segment); return ServerView.CallbackAction.CONTINUE; } @Override public ServerView.CallbackAction segmentViewInitialized() { initialized = true; return ServerView.CallbackAction.CONTINUE; } } ); baseView.registerServerCallback( exec, new ServerView.ServerCallback() { @Override public ServerView.CallbackAction serverRemoved(DruidServer server) { removeServer(server); return ServerView.CallbackAction.CONTINUE; } } ); }

Target:
public CoordinatorServerView( ServerInventoryView baseView ) { this.baseView = baseView; this.segmentLoadInfos = Maps.newHashMap(); this.timelines = Maps.newHashMap(); ExecutorService exec = Execs.singleThreaded("CoordinatorServerView-%s"); baseView.registerSegmentCallback( exec, new ServerView.SegmentCallback() { @Override public ServerView.CallbackAction segmentAdded(DruidServerMetadata server, DataSegment segment) { serverAddedSegment(server, segment); return ServerView.CallbackAction.CONTINUE; } @Override public ServerView.CallbackAction segmentRemoved(final DruidServerMetadata server, DataSegment segment) { serverRemovedSegment(server, segment); return ServerView.CallbackAction.CONTINUE; } @Override public ServerView.CallbackAction segmentViewInitialized() { initialized = true; return ServerView.CallbackAction.CONTINUE; } } ); baseView.registerServerCallback( exec, new ServerView.ServerCallback() { @Override public ServerView.CallbackAction serverRemoved(DruidServer server) { removeServer(server); return ServerView.CallbackAction.CONTINUE; } } ); }
Source:
public List<String> getTimeZoneOptionsAsHtml() { return getTimeZoneOptionsAsHtml(TimeHelper.convertToOffset(timeZone)); }

Target:
public List<String> getTimeZoneOptionsAsHtml() { return getTimeZoneOptionsAsHtml(timeZone); }
Source:
public void deleteFromSubject(String tenant, String subject) { String hql = "DELETE FROM Policy " + "WHERE subject = :subject_id"; Query query = this.currentSession().createQuery(hql); query.setParameter("subject_id", subject); int result = query.executeUpdate(); System.out.println("The result of the delete subject is " + result); }

Target:
public void deleteFromSubject(String tenant, String subject) { String hql = "DELETE FROM Policy " + "WHERE subject = :subject_id"; Query query = this.currentSession().createQuery(hql); query.setParameter("subject_id", subject); int result = query.executeUpdate(); }
Source:
public void testQueryExecution() { VmTemplate expected = new VmTemplate(); VmTemplateDao vmTemplateDaoMock = mock(VmTemplateDao.class); when(vmTemplateDaoMock.getTemplatesWithPermittedAction(getUser().getId(), getActionGroup())).thenReturn(Collections.singletonList(expected)); when(getDbFacadeMockInstance().getVmTemplateDao()).thenReturn(vmTemplateDaoMock); getQuery().executeQueryCommand(); @SuppressWarnings("unchecked") List<VmTemplate> actual = getQuery().getQueryReturnValue().getReturnValue(); assertEquals("Wrong number of VDS Groups", 1, actual.size()); assertEquals("Wrong VDS Groups", expected, actual.get(0)); }

Target:
public void testQueryExecution() { VmTemplate expected = new VmTemplate(); VmTemplateDao vmTemplateDaoMock = mock(VmTemplateDao.class); when(vmTemplateDaoMock.getTemplatesWithPermittedAction(getUser().getId(), getActionGroup())).thenReturn(Collections.singletonList(expected)); when(getDbFacadeMockInstance().getVmTemplateDao()).thenReturn(vmTemplateDaoMock); getQuery().executeQueryCommand(); @SuppressWarnings("unchecked") List<VmTemplate> actual = getQuery().getQueryReturnValue().getReturnValue(); assertEquals("Wrong number of templates", 1, actual.size()); assertEquals("Wrong templates", expected, actual.get(0)); }
Source:
public ProcessorConfig(final List<Evaluator> evaluators, final List<Action> actions, final List<StreamDefinition> streamDefinition, final List<StreamDefinition> writePermitedStreamDefinition, final Aphrodite aphrodite, final ExecutorService executorService, final String rootDirectory, final boolean write) { super(); this.evaluators = evaluators; this.actions = actions; this.aphrodite = aphrodite; this.executorService = executorService; this.streamDefinition = Collections.unmodifiableList(streamDefinition); if(writePermitedStreamDefinition != null){ this.writePermitedStreamDefinition = Collections.unmodifiableList(writePermitedStreamDefinition); } else { this.writePermitedStreamDefinition = this.streamDefinition; } this.rootDirectory = rootDirectory; this.write = write; }

Target:
public ProcessorConfig(final List<Evaluator> evaluators, final List<Action> actions, final List<StreamDefinition> streamDefinition, final List<StreamDefinition> writePermitedStreamDefinition, final Aphrodite aphrodite, final ExecutorService executorService, final String rootDirectory, final boolean write) { super(); this.evaluators = evaluators; this.actions = actions; this.aphrodite = aphrodite; this.executorService = executorService; this.streamDefinition = Collections.unmodifiableList(streamDefinition); if(writePermitedStreamDefinition != null){ this.writePermitedStreamDefinition = Collections.unmodifiableList(writePermitedStreamDefinition); } else { this.writePermitedStreamDefinition = this.streamDefinition; } this.rootDirectory = new File(rootDirectory); this.write = write; }
Source:
public void writeTo(ObjectOutput output) throws IOException { MarshallUtil.marshallEnum(type, output); switch (type) { case START_STATE_TRANSFER: output.writeBoolean(applyState); case GET_TRANSACTIONS: case CANCEL_STATE_TRANSFER: output.writeObject(getOrigin()); MarshallUtil.marshallCollection(segments, output); return; case GET_CACHE_LISTENERS: return; default: throw new IllegalStateException("Unknown state request command type: " + type); } }

Target:
public void writeTo(ObjectOutput output) throws IOException { MarshallUtil.marshallEnum(type, output); switch (type) { case START_CONSISTENCY_CHECK: case CANCEL_CONSISTENCY_CHECK: case START_STATE_TRANSFER: case GET_TRANSACTIONS: case CANCEL_STATE_TRANSFER: output.writeObject(getOrigin()); MarshallUtil.marshallCollection(segments, output); return; case GET_CACHE_LISTENERS: return; default: throw new IllegalStateException("Unknown state request command type: " + type); } }
Source:
public final void setAggregates(GPOMutable aggregates) { Preconditions.checkNotNull(aggregates); this.aggregates = aggregates; }

Target:
protected final void setAggregates(GPOMutable aggregates) { Preconditions.checkNotNull(aggregates); this.aggregates = aggregates; }
Source:
public void setup(TestContext testContext) throws Exception { this.testContext = testContext; targetInstance = testContext.getTargetInstance(); basename = testContext.getTestId(); if (TestUtils.isMemberNode(targetInstance)) { HazelcastServerCachingProvider hcp = new HazelcastServerCachingProvider(); cacheManager = new HazelcastServerCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } else { HazelcastClientCachingProvider hcp = new HazelcastClientCachingProvider(); cacheManager = new HazelcastClientCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } config = new CacheConfig(); config.setName(basename); config.setTypes(Object.class, Object.class); config.setReadThrough(true); config.setCacheLoaderFactory(FactoryBuilder.factoryOf( new RecordingCacheLoader() )); cacheManager.createCache(basename, config); cache = cacheManager.getCache(basename); config = cache.getConfiguration(CacheConfig.class); for(int i=0; i< keyCount; i++){ keySet.add(i); } }

Target:
public void setup(TestContext testContext) throws Exception { this.testContext = testContext; targetInstance = testContext.getTargetInstance(); basename = testContext.getTestId(); if (TestUtils.isMemberNode(targetInstance)) { HazelcastServerCachingProvider hcp = new HazelcastServerCachingProvider(); cacheManager = new HazelcastServerCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } else { HazelcastClientCachingProvider hcp = new HazelcastClientCachingProvider(); cacheManager = new HazelcastClientCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } config = new CacheConfig(); config.setName(basename); config.setReadThrough(true); RecordingCacheLoader recordingCacheLoader = new RecordingCacheLoader(); recordingCacheLoader.loadAllDelayMs = loadAllDelayMs; config.setCacheLoaderFactory(FactoryBuilder.factoryOf( recordingCacheLoader )); cacheManager.createCache(basename, config); cache = cacheManager.getCache(basename); config = cache.getConfiguration(CacheConfig.class); }
Source:
public void testListingWithFallbackLinkWithSameMountDirectoryTree() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(Constants.CONFIG_VIEWFS_MOUNT_LINKS_AS_SYMLINKS, false); ConfigUtil.addLink(conf, "/user1/hive/warehouse/partition-0", new Path(targetTestRoot.toString()).toUri()); Path dir1 = new Path(targetTestRoot, "fallbackDir/user1/hive/warehouse/partition-0"); Path dir2 = new Path(targetTestRoot, "fallbackDir/user1/hive/warehouse1"); fsTarget.mkdirs(dir1); fsTarget.mkdirs(dir2); fsTarget.setPermission(new Path(targetTestRoot, "fallbackDir/user1/hive/"), FsPermission.valueOf("-rwxr--r--")); URI viewFsUri = new URI(FsConstants.VIEWFS_SCHEME, Constants.CONFIG_VIEWFS_DEFAULT_MOUNT_TABLE, "/", null, null); HashSet<Path> beforeFallback = new HashSet<>(); try (FileSystem vfs = FileSystem.get(viewFsUri, conf)) { for (FileStatus stat : vfs .listStatus(new Path(viewFsUri.toString(), "/user1/hive/"))) { beforeFallback.add(stat.getPath()); } } ConfigUtil .addLinkFallback(conf, new Path(targetTestRoot, "fallbackDir").toUri()); try (FileSystem vfs = FileSystem.get(viewFsUri, conf)) { HashSet<Path> afterFallback = new HashSet<>(); for (FileStatus stat : vfs .listStatus(new Path(viewFsUri.toString(), "/user1/hive/"))) { afterFallback.add(stat.getPath()); if (dir1.getName().equals(stat.getPath().getName())) { assertEquals(FsPermission.valueOf("-rwxr--r--"), stat.getPermission()); } } afterFallback.removeAll(beforeFallback); assertTrue("The same directory name in fallback link should be shaded", afterFallback.size() == 1); } }

Target:
public void testListingWithFallbackLinkWithSameMountDirectoryTree() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(Constants.CONFIG_VIEWFS_MOUNT_LINKS_AS_SYMLINKS, false); ConfigUtil.addLink(conf, "/user1/hive/warehouse/partition-0", new Path(targetTestRoot.toString()).toUri()); Path dir1 = new Path(targetTestRoot, "fallbackDir/user1/hive/warehouse/partition-0"); Path dir2 = new Path(targetTestRoot, "fallbackDir/user1/hive/warehouse1"); fsTarget.mkdirs(dir1); fsTarget.mkdirs(dir2); fsTarget.setPermission(new Path(targetTestRoot, "fallbackDir/user1/hive/"), FsPermission.valueOf("-rwxr--r--")); URI viewFsUri = new URI(FsConstants.VIEWFS_SCHEME, Constants.CONFIG_VIEWFS_DEFAULT_MOUNT_TABLE, "/", null, null); HashSet<Path> beforeFallback = new HashSet<>(); try (FileSystem vfs = FileSystem.get(viewFsUri, conf)) { for (FileStatus stat : vfs .listStatus(new Path(viewFsUri.toString(), "/user1/hive/"))) { beforeFallback.add(stat.getPath()); } } ConfigUtil .addLinkFallback(conf, new Path(targetTestRoot, "fallbackDir").toUri()); try (FileSystem vfs = FileSystem.get(viewFsUri, conf)) { HashSet<Path> afterFallback = new HashSet<>(); for (FileStatus stat : vfs .listStatus(new Path(viewFsUri.toString(), "/user1/hive/"))) { afterFallback.add(stat.getPath()); if (dir1.getName().equals(stat.getPath().getName())) { assertEquals(FsPermission.valueOf("-rwxr--r--"), stat.getPermission()); } } afterFallback.removeAll(beforeFallback); assertEquals("The same directory name in fallback link should be shaded", 1, afterFallback.size()); } }
Source:
public void stop() throws InterruptedException { final String container = containerId.or(containerName); stopAsync().awaitTerminated(); try { log.info("container stats: {}", containerName, docker.stats(containerName).toString()); docker.stopContainer(container, secondsToWaitBeforeKill); } catch (DockerException e) { if ((e instanceof ContainerNotFoundException) && !containerId.isPresent()) { } else { log.warn("Stopping container failed", container, e); } } }

Target:
public void stop() throws InterruptedException { final String container = containerId.or(containerName); stopAsync().awaitTerminated(); if (System.getenv("CONTAINER_STATS") != null) { try { log.info("container stats: {}", containerName, docker.stats(containerName)); } catch (DockerException e) { log.warn("Could not log container stats. Exception was {}", e); } } try { docker.stopContainer(container, secondsToWaitBeforeKill); } catch (DockerException e) { if ((e instanceof ContainerNotFoundException) && !containerId.isPresent()) { } else { log.warn("Stopping container failed", container, e); } } }
Source:
public void execCreateTestWithEnv() throws Exception { String containerName = "generated_" + new SecureRandom().nextInt(); final String testVariable = "VARIABLE=success"; CreateContainerResponse container = dockerClient.createContainerCmd("busybox").withUser("root").withCmd("top") .withName(containerName).exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()) .withEnv(testVariable) .withCmd("/bin/sh", "-c", "\"env | grep BASE_DIR\"").exec(); assertThat(execCreateCmdResponse.getId(), not(isEmptyString())); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); dockerClient.execStartCmd(execCreateCmdResponse.getId()) .withDetach(false) .exec(new ExecStartResultCallback(stdout, System.err)) .awaitCompletion(); stdout.close(); assertEquals(stdout.toString(), testVariable); }

Target:
public void execCreateTestWithEnv() throws Exception { String containerName = "generated_" + new SecureRandom().nextInt(); final List<String> testVariable = Arrays.asList("VARIABLE=dockerJavaTestSuccess"); CreateContainerResponse container = dockerClient.createContainerCmd("busybox").withUser("root").withCmd("top") .withName(containerName).exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()) .withEnv(testVariable) .withAttachStdout(true) .withAttachStderr(true) .withCmd("/bin/sh", "-c", "env | grep dockerJavaTestSuccess").exec(); assertThat(execCreateCmdResponse.getId(), not(isEmptyString())); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ExecStartResultCallback callback = new ExecStartResultCallback(stdout, stdout); dockerClient .execStartCmd(execCreateCmdResponse.getId()) .withDetach(false) .exec(callback) .awaitCompletion(); stdout.close(); assertTrue(stdout.toString().startsWith(testVariable.get(0))); }
Source:
synchronized void notifyProgressListener(long listenerId, long transferredBytes, long transferableBytes) { Pair<ProgressListener, Progress> listener = listenerIdToProgressListenerMap.get(listenerId); if (listener != null) { Progress newProgressNotification = new Progress(transferredBytes, transferableBytes); if (!newProgressNotification.equals(listener.second)) { listener.first.onChange(newProgressNotification); listener.second = newProgressNotification; } } else { RealmLog.debug("Trying unknown listener failed: " + listenerId); } }

Target:
synchronized void notifyProgressListener(long listenerId, long transferredBytes, long transferableBytes) { Pair<ProgressListener, Progress> listener = listenerIdToProgressListenerMap.get(listenerId); if (listener != null) { Progress newProgressNotification = new Progress(transferredBytes, transferableBytes); if (!newProgressNotification.equals(listener.second)) { listener.second = newProgressNotification; listener.first.onChange(newProgressNotification); } } else { RealmLog.debug("Trying unknown listener failed: " + listenerId); } }
Source:
public boolean create(final Identifier queryId, final Map<Identifier, OperatorState> queryState) { if (queryStateMap.containsKey(queryId)) { return false; } else { queryStateMap.put(queryId, queryState); return true; } }

Target:
public boolean create(final Identifier queryId, final Map<Identifier, OperatorState> queryState) { return queryStateMap.putIfAbsent(queryId, queryState) == null ? true : false; }
Source:
protected String getLabelForFormsSent() { int successfulSends = getSuccessfulSends(); String label = Localization.get("sync.success.sent", new String[]{String.valueOf(successfulSends)}); if (successfulSends == 1) { label = Localization.get("sync.success.sent.singular", new String[]{String.valueOf(successfulSends)}); } return label; }

Target:
protected String getLabelForFormsSent() { int successfulSends = getSuccessfulSends(); String label; switch (successfulSends) { case 0: label = Localization.get("sync.success.sent.none"); break; case 1: label = Localization.get("sync.success.sent.singular"); break; default: label = Localization.get("sync.success.sent", new String[]{String.valueOf(successfulSends)}); } return label; }
Source:
private void physicalClose() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Closing cached Channel: " + this.target); } if (this.target == null) { return; } try { if (CachingConnectionFactory.this.active && CachingConnectionFactory.this.publisherConfirms) { ExecutorService executorService = (getExecutorService() != null ? getExecutorService() : Executors.newSingleThreadExecutor()); executorService.execute(new Runnable() { @Override public void run() { try { CachedChannelInvocationHandler.this.target.waitForConfirmsOrDie(getCloseTimeout()); CachedChannelInvocationHandler.this.target.close(); } catch (Exception e) { Thread.currentThread().interrupt(); } } }); } else { this.target.close(); } } catch (AlreadyClosedException e) { if (logger.isTraceEnabled()) { logger.trace(this.target + " is already closed"); } } finally { this.target = null; } }

Target:
private void physicalClose() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Closing cached Channel: " + this.target); } if (this.target == null) { return; } try { if (CachingConnectionFactory.this.active && (CachingConnectionFactory.this.publisherConfirms || CachingConnectionFactory.this.publisherReturns)) { ExecutorService executorService = (getExecutorService() != null ? getExecutorService() : Executors.newSingleThreadExecutor()); final Channel channel = CachedChannelInvocationHandler.this.target; executorService.execute(new Runnable() { @Override public void run() { try { if (CachingConnectionFactory.this.publisherConfirms) { channel.waitForConfirmsOrDie(5000); } else { Thread.sleep(5000); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) finally { try { if (channel.isOpen()) { channel.close(); } } catch (IOException e) catch (AlreadyClosedException e) } } }); } else { this.target.close(); } } catch (AlreadyClosedException e) { if (logger.isTraceEnabled()) { logger.trace(this.target + " is already closed"); } } finally { this.target = null; } }
Source:
public void run() { logger.info("Listening for messages using " + transformer); while (socket != null && socket.isConnected()) { try { transformer.read(in, mess -> incomingMess(mess)); } catch (CardshifterSerializationException e) { if(e.getCause() instanceof SocketException) { logger.info("SocketException has happended, closing the socket"); } else { logger.error(e.getMessage(), e); } this.close(); } if (Thread.interrupted()) { logger.info(this + " interrupted"); close(); break; } if (socket.isClosed()) { logger.info(this + " socket closed"); close(); break; } } logger.info("End of run method for " + this); }

Target:
public void run() { logger.info("Listening for messages using " + transformer); while (socket != null && socket.isConnected()) { try { transformer.read(in, mess -> incomingMess(mess)); } catch (CardshifterSerializationException e) { if(e.getCause() instanceof SocketException) { logger.info("SocketException has occurred, closing the socket"); } else { logger.error(e.getMessage(), e); } this.close(); } if (Thread.interrupted()) { logger.info(this + " interrupted"); close(); break; } if (socket.isClosed()) { logger.info(this + " socket closed"); close(); break; } } logger.info("End of run method for " + this); }
Source:
public void reportNotJenkins() throws Exception { home = tempHome(); grabCliJar(); for (String transport: Arrays.asList("-remoting", "-http", "-ssh")) { String url = "<LINK_0>"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int ret = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds( "java", "-Duser.home=" + home, "-jar", jar.getAbsolutePath(), "-s", url, transport, "-user", "asdf", "who-am-i" ).stdout(baos).stderr(baos).join(); assertThat(baos.toString(), containsString("There's no Jenkins running at")); assertNotEquals(0, ret); } }

Target:
public void reportNotJenkins() throws Exception { home = tempHome(); grabCliJar(); String url = r.getURL().toExternalForm() + "not-jenkins/"; for (String transport : Arrays.asList("-remoting", "-http", "-ssh")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int ret = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds( "java", "-Duser.home=" + home, "-jar", jar.getAbsolutePath(), "-s", url, transport, "-user", "asdf", "who-am-i" ).stdout(baos).stderr(baos).join(); assertThat(baos.toString(), containsString("There's no Jenkins running at")); assertNotEquals(0, ret); } }