auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean anyDiffInIndex() throws IOException { Repository repo = getRepository(); TreeWalk treeWalk = new TreeWalk(repo); treeWalk.setRecursive(true); final ObjectId rev = repo.resolve("HEAD"); if (rev!=null) treeWalk.addTree(new RevWalk(repo).parseTree(rev)); treeWalk.addTree(new DirCacheIterator(repo.readDirCache())); treeWalk.setFilter(TreeFilter.ANY_DIFF); return treeWalk.next(); }

Target:
private boolean anyDiffInIndex() throws IOException { final Repository repo = getRepository(); final TreeWalk treeWalk = new TreeWalk(repo); treeWalk.setRecursive(true); final ObjectId rev = repo.resolve("HEAD"); if (rev != null) { treeWalk.addTree(new RevWalk(repo).parseTree(rev)); } treeWalk.addTree(new DirCacheIterator(repo.readDirCache())); treeWalk.setFilter(TreeFilter.ANY_DIFF); return treeWalk.next(); }
Source:
public Iterable<VMImage> listImages() { final List<VMImage> osImages = Lists.newArrayList(); final List<String> locationIds = Lists.newArrayList(); for (Location location : listLocations()){ locationIds.add(location.name()); osImages.addAll(listImagesByLocation(location.name())); } checkAndSetImageAvailability(osImages, Sets.newHashSet(locationIds)); String offer = ""; List<StorageService> storages = api.getStorageAccountApi(azureGroup).list(); for (StorageService storage : storages) { String name = storage.name(); String key = api.getStorageAccountApi(azureGroup).getKeys(name).key1(); offer = "custom"; List<VMImage> images = BlobHelper.getImages("jclouds", azureGroup, storage.name(), key, offer, storage.location()); osImages.addAll(images); } return osImages; }

Target:
public Iterable<VMImage> listImages() { final List<VMImage> osImages = Lists.newArrayList(); final List<String> locationIds = Lists.newArrayList(); for (Location location : listLocations()){ locationIds.add(location.name()); osImages.addAll(listImagesByLocation(location.name())); } checkAndSetImageAvailability(osImages, Sets.newHashSet(locationIds)); List<StorageService> storages = api.getStorageAccountApi(azureGroup).list(); for (StorageService storage : storages) { String name = storage.name(); String key = api.getStorageAccountApi(azureGroup).getKeys(name).key1(); List<VMImage> images = BlobHelper.getImages("jclouds", azureGroup, storage.name(), key, "custom", storage.location()); osImages.addAll(images); } return osImages; }
Source:
public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeInt(durability); out.writeInt(capacity); out.writeInt(poolSize); out.writeUTF(splitBrainProtectionName); out.writeObject(mergePolicyConfig); out.writeInt(capacityPolicy.ordinal()); }

Target:
public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); out.writeInt(durability); out.writeInt(capacity); out.writeInt(poolSize); out.writeUTF(splitBrainProtectionName); out.writeObject(mergePolicyConfig); out.writeByte(capacityPolicy.getId()); }
Source:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable tvp1 = args[0]; if (!((tvp1.getTag() == ValueTag.OBJECT_TAG) || (tvp1.getTag() == ValueTag.ARRAY_TAG))) { throw new SystemException(ErrorCode.FORG0006); } if (tvp1.getTag() == ValueTag.OBJECT_TAG) { try { tvp1.getValue(op); op.getKeys(result); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } } else if (tvp1.getTag() == ValueTag.ARRAY_TAG) { abvs.reset(); sb.reset(abvs); TaggedValuePointable tempTvp = (TaggedValuePointable) TaggedValuePointable.FACTORY.createPointable(); tvp1.getValue(ap); tvp1.getValue(sp); int size = sp.getEntryCount(); for (int i = 0; i < size; i++) { sp.getEntry(i, tempTvp); try { sb.addItem(tempTvp); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } } try { sb.finish(); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } result.set(abvs); } }

Target:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable tvp1 = args[0]; if (!((tvp1.getTag() == ValueTag.OBJECT_TAG) || (tvp1.getTag() == ValueTag.ARRAY_TAG))) { throw new SystemException(ErrorCode.FORG0006); } if (tvp1.getTag() == ValueTag.OBJECT_TAG) { try { tvp1.getValue(op); op.getKeys(result); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } } else if (tvp1.getTag() == ValueTag.ARRAY_TAG) { abvs.reset(); sb.reset(abvs); tvp1.getValue(ap); tvp1.getValue(sp); int size = sp.getEntryCount(); for (int i = 0; i < size; i++) { sp.getEntry(i, tempTvp); try { sb.addItem(tempTvp); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } } try { sb.finish(); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } result.set(abvs); } }
Source:
public static Results analyze(final WebDriver webDriver, final WebElement context, final AxeBuilderOptions axeBuilderOptions) throws OperationNotSupportedException, IOException { if (webDriver == null) { throw new NullPointerException("the web Driver is null"); } if (context == null) { throw new NullPointerException("the web Element is null"); } AxeBuilder axeBuilder = new AxeBuilder(axeBuilderOptions); return axeBuilder.analyze(webDriver, context); }

Target:
public static Results analyze(final WebDriver webDriver, final WebElement context, final AxeBuilderOptions axeBuilderOptions) throws OperationNotSupportedException, IOException { if (webDriver == null) { throw new NullPointerException("the web Driver is null"); } if (context == null) { throw new NullPointerException("the context is null"); } AxeBuilder axeBuilder = new AxeBuilder(axeBuilderOptions); return axeBuilder.analyze(webDriver, context); }
Source:
public void sparse() { Random r = new Random(); LinkedList<Instance> trainSparseVectors = new LinkedList(); LinkedList<Instance> trainDenseVectors = new LinkedList(); for (int instance = 0; instance < 1000; instance++) { HashMapAttributes sparseInstanceHmAttributes = new HashMapAttributes(); HashMapAttributes denseInstanceHmAttributes = new HashMapAttributes(); for (int feat = 0; feat < 1000; feat++) { String key = ((Integer)feat).toString(); if(feat == instance){ denseInstanceHmAttributes.put(key, 1.0); denseInstanceHmAttributes.put(key, 1.0); } else denseInstanceHmAttributes.put(key, 0); } final Serializable label = r.nextBoolean(); trainSparseVectors.add(sparseInstanceHmAttributes.classification(label.toString())); trainDenseVectors.add(denseInstanceHmAttributes.classification(label.toString())); } { TreeBuilder treeBuilder = new TreeBuilder(); long start = System.currentTimeMillis(); Tree tree = treeBuilder.buildPredictiveModel(trainSparseVectors); System.out.println("Training with sparse vectors took: " + (System.currentTimeMillis()-start) + " milliseconds"); tree.node.dump(System.out); } { TreeBuilder treeBuilder = new TreeBuilder(); long start = System.currentTimeMillis(); Tree tree = treeBuilder.buildPredictiveModel(trainDenseVectors); System.out.println("Training with dense vectors took: " + (System.currentTimeMillis()-start) + " milliseconds"); tree.node.dump(System.out); } System.exit(0); }

Target:
public void sparse() { Random r = new Random(); LinkedList<Instance> trainSparseVectors = new LinkedList(); LinkedList<Instance> trainDenseVectors = new LinkedList(); for (int instance = 0; instance < 1000; instance++) { HashMapAttributes sparseInstanceHmAttributes = new HashMapAttributes(); HashMapAttributes denseInstanceHmAttributes = new HashMapAttributes(); for (int feat = 0; feat < 1000; feat++) { String key = ((Integer)feat).toString(); if(feat == instance){ denseInstanceHmAttributes.put(key, 1.0); sparseInstanceHmAttributes.put(key, 1.0); } else denseInstanceHmAttributes.put(key, 0); } final Serializable label = r.nextBoolean(); trainSparseVectors.add(sparseInstanceHmAttributes.classification(label.toString())); trainDenseVectors.add(denseInstanceHmAttributes.classification(label.toString())); } { TreeBuilder treeBuilder = new TreeBuilder(); long start = System.currentTimeMillis(); Tree tree = treeBuilder.buildPredictiveModel(trainSparseVectors); System.out.println("Training with sparse vectors took: " + (System.currentTimeMillis()-start) + " milliseconds"); tree.node.dump(System.out); } { TreeBuilder treeBuilder = new TreeBuilder(); long start = System.currentTimeMillis(); Tree tree = treeBuilder.buildPredictiveModel(trainDenseVectors); System.out.println("Training with dense vectors took: " + (System.currentTimeMillis()-start) + " milliseconds"); tree.node.dump(System.out); } System.exit(0); }
Source:
public Receive createReceive() { return new ReceiveBuilder() .matchEquals(FETCH_METRIC, work -> _metricsDiscovery.tell(MetricFetch.getInstance(), getSelf())) .match(String.class, this::fetchMetricTags) .match(TagNamesMessage.class, this::handleTagNamesMessage) .match(LastDataPointMessage.class, this::handleLastDataPointMessage) .match(FinishRollupMessage.class, this::handleFinishRollupMessage) .match(NoMoreMetrics.class, noMore -> timers().startSingleTimer("sleepTimer", FETCH_METRIC, _fetchBackoff)) .build(); }

Target:
public Receive createReceive() { return new ReceiveBuilder() .matchEquals(FETCH_METRIC, this::handleFetchMetrics) .match(String.class, this::fetchMetricTags) .match(TagNamesMessage.class, this::handleTagNamesMessage) .match(LastDataPointMessage.class, this::handleLastDataPointMessage) .match(FinishRollupMessage.class, this::handleFinishRollupMessage) .match(NoMoreMetrics.class, this::handleNoMoreMetricsMessage) .build(); }
Source:
private RuntimeException closeRestoring(final boolean isZombie, final StreamTask task, final List<TopicPartition> closedTaskChangelogs) { removeTaskFromRestoring(task); closedTaskChangelogs.addAll(task.changelogPartitions()); try { final boolean clean = !isZombie; task.closeStateManager(clean); } catch (final RuntimeException e) { log.error("Failed to close restoring task due to the following error:", task.id(), e); return e; } return null; }

Target:
private RuntimeException closeRestoring(final boolean isZombie, final StreamTask task, final List<TopicPartition> closedTaskChangelogs) { removeTaskFromRestoring(task); closedTaskChangelogs.addAll(task.changelogPartitions()); try { final boolean clean = !isZombie; task.closeStateManager(clean); } catch (final RuntimeException e) { log.error("Failed to close the restoring stream task due to the following error:", task.id(), e); return e; } return null; }
Source:
public void testExtendingDiskWithQuota() { Guid quotaId = Guid.newGuid(); DiskImage oldDiskImage = createDiskImage(); oldDiskImage.setQuotaId(quotaId); oldDiskImage.setSize(getBytesByGB(3)); DiskImage newDiskImage = createDiskImage(); newDiskImage.setQuotaId(quotaId); newDiskImage.setSize(getBytesByGB(5)); UpdateVmDiskParameters parameters = new UpdateVmDiskParameters(vmId, diskImageGuid, newDiskImage); long diskExtendingDiffInGB = newDiskImage.getSizeInGigabytes() - oldDiskImage.getSizeInGigabytes(); when(diskDao.get(diskImageGuid)).thenReturn(oldDiskImage); initializeCommand(parameters); QuotaStorageConsumptionParameter consumptionParameter = (QuotaStorageConsumptionParameter) command.getQuotaStorageConsumptionParameters().get(0); assertTrue(consumptionParameter.getRequestedStorageGB() == diskExtendingDiffInGB); }

Target:
public void testExtendingDiskWithQuota() { Guid quotaId = Guid.newGuid(); DiskImage oldDiskImage = createDiskImage(); oldDiskImage.setQuotaId(quotaId); oldDiskImage.setSize(SizeConverter.convert(3, SizeConverter.SizeUnit.GB, SizeConverter.SizeUnit.BYTES).longValue()); DiskImage newDiskImage = createDiskImage(); newDiskImage.setQuotaId(quotaId); newDiskImage.setSize(SizeConverter.convert(5, SizeConverter.SizeUnit.GB, SizeConverter.SizeUnit.BYTES).longValue()); UpdateVmDiskParameters parameters = new UpdateVmDiskParameters(vmId, diskImageGuid, newDiskImage); long diskExtendingDiffInGB = newDiskImage.getSizeInGigabytes() - oldDiskImage.getSizeInGigabytes(); when(diskDao.get(diskImageGuid)).thenReturn(oldDiskImage); initializeCommand(parameters); QuotaStorageConsumptionParameter consumptionParameter = (QuotaStorageConsumptionParameter) command.getQuotaStorageConsumptionParameters().get(0); assertEquals(consumptionParameter.getRequestedStorageGB().longValue(), diskExtendingDiffInGB); }
Source:
public static INDArray forceCorrectShape(INDArray source) { long[] shape = source.shape(); if (shape[0] == 1) { return source; } long[] newShape = new long[shape.length + 1]; newShape[0] = 1; System.arraycopy(shape, 0, newShape, 1, shape.length); return source.reshape(newShape); }

Target:
public static INDArray forceCorrectShape(INDArray source) { return source.shape()[0] == 1 ? source : Nd4j.expandDims(source, 0); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GatewayAccount that = (GatewayAccount) o; return new EqualsBuilder() .append(id, that.id) .append(gatewayName, that.gatewayName) .append(credentials, that.credentials) .isEquals(); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GatewayAccount that = (GatewayAccount) o; return Objects.equals(id, that.id) && Objects.equals(gatewayName, that.gatewayName) && Objects.equals(credentials, that.credentials); }
Source:
protected MessageBus getMessageBus() throws Exception { throw new IllegalStateException("Subclasses must override getMessageBus()"); }

Target:
protected abstract MessageBus getMessageBus() throws Exception; @After public void cleanup() { if (testMessageBus != null) { testMessageBus.cleanup(); } }
Source:
public static List<Region> parseRegions(String regionsString) { List<Region> regions = null; if (regionsString != null && !regionsString.equals("")) { String[] regionItems = regionsString.split(","); regions = new ArrayList<>(regionItems.length); String[] fields; for (String regionString : regionItems) { if (regionString.indexOf(':') != -1) { fields = regionString.split("[:-]", -1); if (fields.length == 3) { regions.add(new Region(fields[0], Integer.parseInt(fields[1]), Integer.parseInt(fields[2]))); } else { regions.add(null); } } else { regions.add(new Region(regionString, 0, Integer.MAX_VALUE)); } } } return regions; }

Target:
public static List<Region> parseRegions(String regionsString) { List<Region> regions = null; if (regionsString != null && !regionsString.equals("")) { String[] regionItems = regionsString.split(","); regions = new ArrayList<>(regionItems.length); String[] fields; for (String regionString : regionItems) { if (regionString.indexOf(':') != -1) { fields = regionString.split("[:-]", -1); if (fields.length == 3) { regions.add(new Region(fields[0], Integer.parseInt(fields[1]), Integer.parseInt(fields[2]))); } else { regions.add(null); } } else { regions.add(new Region(regionString)); } } } return regions; }
Source:
public String toString() { StringBuilder stringRepresentation = new StringBuilder(); getSingleYear().ifPresent(singleYear -> stringRepresentation.append(singleYear).append(" ")); getFromYear().ifPresent(fromYear -> stringRepresentation.append(fromYear).append(" ")); getToYear().ifPresent(toYear -> stringRepresentation.append(toYear).append(" ")); getJournal().ifPresent(journal -> stringRepresentation.append(journal).append(" ")); stringRepresentation.append(String.join(" ", getTitlePhrases())) .append(String.join(" ", getDefaultFieldPhrases())) .append(String.join(" ", getAuthors())) .append(String.join(" ", getAbstractPhrases())); return stringRepresentation.toString(); }

Target:
public String toString() { StringJoiner stringJoiner = new StringJoiner(" "); getSingleYear().ifPresent(singleYear -> stringJoiner.add(singleYear.toString())); getFromYear().ifPresent(fromYear -> stringJoiner.add(fromYear.toString())); getToYear().ifPresent(toYear -> stringJoiner.add(toYear.toString())); getJournal().ifPresent(stringJoiner::add); stringJoiner.add(String.join(" ", getTitlePhrases())) .add(String.join(" ", getDefaultFieldPhrases())) .add(String.join(" ", getAuthors())) .add(String.join(" ", getAbstractPhrases())); return stringJoiner.toString(); }
Source:
public GlusterServersListReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); List<GlusterServerInfo> glusterServers = new ArrayList<GlusterServerInfo>(); if (mStatus.mCode != 0) { Object[] serversArr = (Object[]) innerMap.get(GLUSTER_HOSTS); if (serversArr != null) { for (int i = 0; i < serversArr.length; i++) { glusterServers.add(prepareServerInfo((Map<String, Object>) serversArr[i])); } } } this.servers = glusterServers; }

Target:
public GlusterServersListReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); if (mStatus.mCode != 0) { return; } Object[] serversArr = (Object[]) innerMap.get(GLUSTER_HOSTS); if (serversArr != null) { for (int i = 0; i < serversArr.length; i++) { this.servers.add(prepareServerInfo((Map<String, Object>) serversArr[i])); } } }
Source:
public static int byteArrayToInt(byte[] b) { byte[] values = b; if (b.length < 4) { values = new byte[4]; int diff = 4 - b.length; for (int i = 0; i < diff; i++) values[i] = 0; for (int i = diff; i < 4; i++) values[i] = b[i - diff]; } return ((values[0] & 0xFF) << 24) | ((values[1] & 0xFF) << 16) | ((values[2] & 0xFF) << 8) | (values[3] & 0xFF); }

Target:
public static int byteArrayToInt(byte[] b) { if (b == null) throw new NullPointerException("Byte array cannot be null."); byte[] values = b; if (b.length < 4) { values = new byte[4]; int diff = 4 - b.length; for (int i = 0; i < diff; i++) values[i] = 0; for (int i = diff; i < 4; i++) values[i] = b[i - diff]; } return ((values[0] & 0xFF) << 24) | ((values[1] & 0xFF) << 16) | ((values[2] & 0xFF) << 8) | (values[3] & 0xFF); }
Source:
public void setMinWriteDelay(int minWriteDelay) { if (minWriteDelay < 0) { throw new IllegalArgumentException("Minimum write delay seconds cannot be less than 0"); } else if (minWriteDelay > maxWriteDelay) { throw new IllegalArgumentException("Minimum write delay must be smaller than maximum write delay"); } this.minWriteDelay = minWriteDelay; }

Target:
public void setMinWriteDelay(int minWriteDelay) { if (minWriteDelay < 0) { throw new IllegalArgumentException("Minimum write delay seconds cannot be less than 0"); } else if (minWriteDelay > maxWriteDelay) { throw new IllegalArgumentException("Minimum write delay (" + minWriteDelay + ") must be smaller than or equal to maximum write delay (" + maxWriteDelay + ")"); } this.minWriteDelay = minWriteDelay; }
Source:
public AttestationResult validateHostIsTrusted(VDS vds) { log.debug("begin to validate " + vds.getName()); AttestationResult result = AttestationResult.UNKNOWN; String key = vds.gethost_name(); if (AttestationCacheManager.exists(key)){ if (!AttestationCacheManager.isExpired(key)){ AttestationValue value = AttestationCacheManager.getValueFromCache(key); return value.getTrustLevel(); } else{ for (AttestationValue value : attestHosts(AttestationCacheManager.getAllKeys())){ AttestationCacheManager.updateCache(value); } return AttestationCacheManager.getValueFromCache(key).getTrustLevel(); } } return result; }

Target:
public AttestationResultEnum validateHostIsTrusted(VDS vds) { log.debug("begin to validate " + vds.getName()); AttestationResultEnum result = AttestationResultEnum.UNKNOWN; AttestationCacheManager cacheManager = AttestationCacheManager.getInstance(); String key = vds.gethost_name(); if (cacheManager.exists(key)) { if (!cacheManager.isExpired(key)) { AttestationValue value = cacheManager.getValueFromCache(key); return value.getTrustLevel(); } else { for (AttestationValue value : attestHosts(cacheManager.getAllKeys())) { cacheManager.updateCache(value); } return cacheManager.getValueFromCache(key).getTrustLevel(); } } return result; }
Source:
public void verifyFacebookWindow() { CommonFunctions.waitForWindow("", ""); Object[] windows = driver.getWindowHandles().toArray(); driver.switchTo().window(windows[1].toString()); waitForStringInURL("facebook.com"); driver.close(); driver.switchTo().window(windows[0].toString()); PageObjectLogging.log("verifyFacebookWindow", "Verify that the FB window URL is correct", true, driver); }

Target:
public void verifyFacebookWindow() { CommonFunctions.waitForWindow("", ""); Object[] windows = driver.getWindowHandles().toArray(); driver.switchTo().window(windows[1].toString()); waitForStringInURL(URLsContent.facebookDomain); driver.close(); driver.switchTo().window(windows[0].toString()); PageObjectLogging.log("verifyFacebookWindow", "Verify that the FB window URL is correct", true, driver); }
Source:
protected void configureServlets() { bind(KeycloakAuthenticationFilter.class).in(Singleton.class); filterRegex( "^(?!.*(/docs/))(?!.*(/settings/?|/api/oauth/callback/?)$).*") .through(KeycloakAuthenticationFilter.class); filterRegex( "^(?!.*(/docs/))(?!.*(/settings/?|/api/oauth/callback/?)$).*") .through(KeycloakEnvironmentInitalizationFilter.class); }

Target:
protected void configureServlets() { bind(KeycloakAuthenticationFilter.class).in(Singleton.class); filterRegex("^(?!.*(/docs/))(?!.*(/keycloak/settings/?|/api/oauth/callback/?)$).*") .through(KeycloakAuthenticationFilter.class); filterRegex("^(?!.*(/docs/))(?!.*(/keycloak/settings/?|/api/oauth/callback/?)$).*") .through(KeycloakEnvironmentInitalizationFilter.class); }
Source:
private void initializeDbTable() { try{ metricStore.deleteTrustedExtensionMetadata(TRUSTED_EXTENSION); List<String> extensions = getExtensions(); for (String extension : extensions) { String extensionType = AbstractExtension.isExtensionTrusted(extension) ? TRUSTED_EXTENSION : CUSTOM_EXTENSION; String description = getShortDescription(extension); String recipeName = extension; String location = storePath.toString() + '/' + extension; metricStore.storeExtensionMetadataBean(recipeName, location, extensionType, description); } } catch (FalconException e){ LOG.error("Exception in ExtensionStore:", e); throw new RuntimeException(e); } }

Target:
private void initializeDbTable() { try{ metaStore.deleteExtensionsOfType(ExtensionType.TRUSTED); List<String> extensions = getExtensions(); for (String extension : extensions) { ExtensionType extensionType = AbstractExtension.isExtensionTrusted(extension) ? ExtensionType.TRUSTED : ExtensionType.CUSTOM; String description = getShortDescription(extension); String recipeName = extension; String location = storePath.toString() + '/' + extension; metaStore.storeExtensionMetadataBean(recipeName, location, extensionType, description); } } catch (FalconException e){ LOG.error("Exception in ExtensionStore:", e); throw new RuntimeException(e); } }
Source:
public static <C extends ColumnType> Builder<C> newBuilder(ColumnTypeRegistry<C> src) { final Builder<C> builder = new Builder<>(); builder.columnTypeMap.putAll(src.columnTypeMap); return builder; }

Target:
public static <C extends ColumnType> Builder<C> newBuilder(ColumnTypeRegistry<C> src) { final Builder<C> builder = newBuilder(); for (Map.Entry<Class, C> typeMapping : src.columnTypeMap.entrySet()) { builder.put(typeMapping.getKey(), typeMapping.getValue()); } return builder; }
Source:
private Plugin loadPlugin(String name, File srcJar, FileSnapshot snapshot) throws IOException, ClassNotFoundException, InvalidPluginException { File tmp; FileInputStream in = new FileInputStream(srcJar); try { tmp = asTemp(in, tempNameFor(name), ".jar", tmpDir); } finally { in.close(); } JarFile jarFile = new JarFile(tmp); boolean keep = false; try { Manifest manifest = jarFile.getManifest(); Plugin.ApiType type = Plugin.getApiType(manifest); Attributes main = manifest.getMainAttributes(); String sysName = main.getValue("Gerrit-Module"); String sshName = main.getValue("Gerrit-SshModule"); String httpName = main.getValue("Gerrit-HttpModule"); String webName = main.getValue("Web-HttpModule"); if (!Strings.isNullOrEmpty(sshName) && type != Plugin.ApiType.PLUGIN) { throw new InvalidPluginException(String.format( "Using Gerrit-SshModule requires Gerrit-ApiType: %s", Plugin.ApiType.PLUGIN)); } URL[] urls = {tmp.toURI().toURL()}; ClassLoader parentLoader = parentFor(type); ClassLoader pluginLoader = new URLClassLoader(urls, parentLoader); cleanupHandles.put( new CleanupHandle(tmp, jarFile, pluginLoader, cleanupQueue), Boolean.TRUE); Class<? extends Module> sysModule = load(sysName, pluginLoader); Class<? extends Module> sshModule = load(sshName, pluginLoader); Class<? extends Module> httpModule = load(httpName, pluginLoader); keep = true; return new Plugin(name, srcJar, snapshot, jarFile, manifest, new File(dataDir, name), type, pluginLoader, sysModule, sshModule, httpModule); } finally { if (!keep) { jarFile.close(); } } }

Target:
private Plugin loadPlugin(String name, File srcJar, FileSnapshot snapshot) throws IOException, ClassNotFoundException, InvalidPluginException { File tmp; FileInputStream in = new FileInputStream(srcJar); try { tmp = asTemp(in, tempNameFor(name), ".jar", tmpDir); } finally { in.close(); } JarFile jarFile = new JarFile(tmp); boolean keep = false; try { Manifest manifest = jarFile.getManifest(); Plugin.ApiType type = Plugin.getApiType(manifest); Attributes main = manifest.getMainAttributes(); String sysName = main.getValue("Gerrit-Module"); String sshName = main.getValue("Gerrit-SshModule"); String httpName = main.getValue("Gerrit-HttpModule"); if (!Strings.isNullOrEmpty(sshName) && type != Plugin.ApiType.PLUGIN) { throw new InvalidPluginException(String.format( "Using Gerrit-SshModule requires Gerrit-ApiType: %s", Plugin.ApiType.PLUGIN)); } URL[] urls = {tmp.toURI().toURL()}; ClassLoader parentLoader = parentFor(type); ClassLoader pluginLoader = new URLClassLoader(urls, parentLoader); cleanupHandles.put( new CleanupHandle(tmp, jarFile, pluginLoader, cleanupQueue), Boolean.TRUE); Class<? extends Module> sysModule = load(sysName, pluginLoader); Class<? extends Module> sshModule = load(sshName, pluginLoader); Class<? extends Module> httpModule = load(httpName, pluginLoader); keep = true; return new Plugin(name, srcJar, snapshot, jarFile, manifest, new File(dataDir, name), type, pluginLoader, sysModule, sshModule, httpModule); } finally { if (!keep) { jarFile.close(); } } }
Source:
public void Authenticate(String authUser, String authPassword) throws AuthenticationException { if (!userName.equals(authUser)) { throw new AuthenticationException("Invalid user " + authUser); } if (!password.equals(authPassword)) { throw new AuthenticationException("Invalid password " + authPassword); } LOG.info("User " + authUser + " successfully authenticated."); }

Target:
public void Authenticate(String authUser, String authPassword) throws AuthenticationException { if (!userName.equals(authUser)) { LOG.debug("Invalid user " + authUser); throw new AuthenticationException("Invalid credentials"); } if (!password.equals(authPassword)) { LOG.debug("Invalid password for user " + authUser); throw new AuthenticationException("Invalid credentials"); } LOG.debug("User " + authUser + " successfully authenticated."); }
Source:
public void apply(OnlineCommandContext ctx) throws Exception { Operations ops = new Operations(ctx.client); if(allowResourceServiceRestart) ops = ops.headers(Values.of("allow-resource-service-restart", "true")); ops.remove(address); }

Target:
public void apply(OnlineCommandContext ctx) throws Exception { Operations ops = new Operations(ctx.client); if (ctx.version.greaterThanOrEqualTo(ServerVersion.VERSION_5_0_0)) ops = ops.headers(Headers.allowResourceServiceRestart()); ops.remove(address); }
Source:
public void testMakingAttachment() { testMakingAttachmentFile("attachment.txt","normal text file") }

Target:
public void testMakingAttachment() { testMakingAttachmentFile("attachment.txt","normal text file"); }
Source:
public void testCreateReadDelete() throws Exception { DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", USERNAME); userModel = userManager.createUser(userModel); DocumentModel folder = systemSession.createDocumentModel("/", "folder", "Folder"); folder = systemSession.createDocument(folder); DocumentModel doc = systemSession.createDocumentModel("/folder/", "TestFile", "File"); doc = systemSession.createDocument(doc); ACP acp = doc.getACP(); ACE grantRead = new ACE(USERNAME, SecurityConstants.READ, true); acp.addACE(ACL.LOCAL_ACL, grantRead); doc.setACP(acp, true); try (CoreSession userSession = coreFeature.openCoreSession(USERNAME)) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); DocumentModel comment = userSession.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); comment.setPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH, COMMENT_CONTENT); commentManager.createComment(userDoc, comment); List<DocumentModel> dml = systemSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(1, dml.size()); dml = userSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(0, dml.size()); List<DocumentModel> comments = commentManager.getComments(userDoc); assertEquals(1, comments.size()); assertEquals(COMMENT_CONTENT, comments.get(0).getPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH)); commentManager.deleteComment(userDoc, comments.get(0)); comments = commentManager.getComments(userDoc); assertEquals(0, comments.size()); } }

Target:
public void testCreateReadDelete() { DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", USERNAME); DocumentModel folder = systemSession.createDocumentModel("/", "folder", "Folder"); systemSession.createDocument(folder); DocumentModel doc = systemSession.createDocumentModel("/folder/", "TestFile", "File"); doc = systemSession.createDocument(doc); ACP acp = doc.getACP(); ACE grantRead = new ACE(USERNAME, SecurityConstants.READ, true); acp.addACE(ACL.LOCAL_ACL, grantRead); doc.setACP(acp, true); try (CoreSession userSession = coreFeature.openCoreSession(USERNAME)) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); DocumentModel comment = userSession.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); comment.setPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH, COMMENT_CONTENT); commentManager.createComment(userDoc, comment); List<DocumentModel> dml = systemSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(1, dml.size()); dml = userSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(0, dml.size()); List<DocumentModel> comments = commentManager.getComments(userDoc); assertEquals(1, comments.size()); assertEquals(COMMENT_CONTENT, comments.get(0).getPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH)); commentManager.deleteComment(userDoc, comments.get(0)); comments = commentManager.getComments(userDoc); assertEquals(0, comments.size()); } }
Source:
public void buildShellScript() throws Exception { story.addStep( new Statement() { @Override public void evaluate() throws Throwable { Node node = TestUtils.createSwarmClient( story.j, processDestroyer, tmpDir.allocate()); WorkflowJob project = story.j.createProject(WorkflowJob.class); project.setConcurrentBuild(false); project.setDefinition(new CpsFlowDefinition(getFlow(node, 0), true)); WorkflowRun build = project.scheduleBuild2(0).waitForStart(); story.j.waitForCompletion(build); story.j.assertLogContains("ON_SWARM_CLIENT=true", build); story.j.assertBuildStatusSuccess(build); tearDown(); } }); }

Target:
public void buildShellScript() throws Exception { story.then( s -> { Node node = TestUtils.createSwarmClient(story.j, processDestroyer, temporaryFolder); WorkflowJob project = story.j.createProject(WorkflowJob.class); project.setConcurrentBuild(false); project.setDefinition(new CpsFlowDefinition(getFlow(node, 0), true)); WorkflowRun build = story.j.buildAndAssertSuccess(project); story.j.assertLogContains("ON_SWARM_CLIENT=true", build); tearDown(); }); }
Source:
private <T> T provideUnchecked(final Class<T> serviceClass) { final Registration<T> registration = (Registration<T>) this.services.get(serviceClass); if (registration != null) { return registration.service(); } throw new IllegalStateException(""); }

Target:
private <T> T provideUnchecked(final Class<T> serviceClass) { final Registration<T> registration = (Registration<T>) this.services.get(serviceClass); if (registration != null) { return registration.service(); } throw new IllegalStateException("Service registration does not exist."); }
Source:
public void update(float delta) { if (contents != null) { contents.update(delta); animationSystem.update(delta); if (depth == -999999) { setDepthAuto(); } } }

Target:
public void update(float delta) { if (contents != null) { contents.update(delta); animationSystem.update(delta); if (depth == SortOrderSystem.DEFAULT_DEPTH) { setDepthAuto(); } } }
Source:
@Override public Map<UUID, Integer> topologySnapshot() { return top; }

Target:
@Override public Map<UUID, Integer> topologySnapshot() { return Collections.unmodifiableMap(top); }
Source:
private void checkAttributes(Map<String, Object> attributes) { if (attributes == null) { throw new IllegalArgumentException("Attributes must be non null"); } }

Target:
private void checkAttributes(Map<String, Object> attributes) { if (attributes == null) { throw new IllegalArgumentException("Attributes must be not null"); } }
Source:
public BlockFamily createFamily(BlockBuilderHelper blockBuilderHelper) { Preconditions.checkState(!isFreeform()); return BlockfamilyLibrary.createFamily(getData().getBlockFamily(), this, blockBuilderHelper); }

Target:
public BlockFamily createFamily(BlockBuilderHelper blockBuilderHelper) { Preconditions.checkState(!isFreeform()); return BlockFamilyLibrary.createFamily(getData().getBlockFamily(), this, blockBuilderHelper); }
Source:
@Test public void staticCodeBlock() { TypeSpec taco = TypeSpec.classBuilder("Taco") .addField(String.class, "mFoo", Modifier.PRIVATE) .addField(String.class, "FOO", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .addStaticBlock(CodeBlock.builder() .addStatement("FOO = $S", "FOO") .build()) .addMethod(MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addCode("return FOO;\n") .build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.Override;\n" + "import java.lang.String;\n" + "\n" + "class Taco {\n" + " private static final String FOO;\n\n" + " static {\n" + " FOO = \"FOO\";\n" + " }\n\n" + " private String mFoo;\n\n" + " @Override\n" + " public String toString() {\n" + " return FOO;\n" + " }\n" + "}\n"); }

Target:
@Test public void staticCodeBlock() { TypeSpec taco = TypeSpec.classBuilder("Taco") .addField(String.class, "foo", Modifier.PRIVATE) .addField(String.class, "FOO", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .addStaticBlock(CodeBlock.builder() .addStatement("FOO = $S", "FOO") .build()) .addMethod(MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(String.class) .addCode("return FOO;\n") .build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.Override;\n" + "import java.lang.String;\n" + "\n" + "class Taco {\n" + " private static final String FOO;\n" + "\n" + " static {\n" + " FOO = \"FOO\";\n" + " }\n" + "\n" + " private String foo;\n" + "\n" + " @Override\n" + " public String toString() {\n" + " return FOO;\n" + " }\n" + "}\n"); }
Source:
private Command getPropertyPublicPart(RepositoryNode selectedNode, IElementParameter param, Node node, ConnectionItem connectionItem) { param.getChildParameters().get(EParameterName.PROPERTY_TYPE.getName()).setValue(EmfComponent.REPOSITORY); ChangeValuesFromRepository command2 = new ChangeValuesFromRepository( node, connectionItem.getConnection(), param.getName() + ":" + EParameterName.REPOSITORY_PROPERTY_TYPE.getName(), selectedNode.getObject().getProperty().getId()); if (selectedNode.getObject() instanceof IMetadataTable) { IMetadataTable metadataTable = (IMetadataTable) selectedNode.getObject(); command2.setTable(metadataTable); } if (selectedNode.getProperties(EProperties.CONTENT_TYPE) == ERepositoryObjectType.METADATA_CONNECTIONS) { command2.setGuessQuery(true); } return command2; }

Target:
private Command getPropertyPublicPart(RepositoryNode selectedNode, IElementParameter param, Node node, ConnectionItem connectionItem) { param.getChildParameters().get(EParameterName.PROPERTY_TYPE.getName()).setValue(EmfComponent.REPOSITORY); ChangeValuesFromRepository command2 = new ChangeValuesFromRepository( node, connectionItem.getConnection(), param.getName() + ":" + EParameterName.REPOSITORY_PROPERTY_TYPE.getName(), selectedNode.getObject().getProperty().getId()); if (selectedNode.getObject() instanceof IMetadataTable) { IMetadataTable metadataTable = (IMetadataTable) selectedNode.getObject(); command2.setTable(metadataTable); } if (selectedNode.getProperties(EProperties.CONTENT_TYPE) != ERepositoryObjectType.METADATA_CON_QUERY) { command2.setGuessQuery(true); } return command2; }
Source:
public void testCoordinatorFailed() throws Exception { startGrids(NODES_CNT); CountDownLatch startLatch = new CountDownLatch(NODES_CNT); CountDownLatch finishLatch = new CountDownLatch(NODES_CNT - 1); HashMap<String, DistributedProcess<Integer, Integer>> processes = new HashMap<>(); int processRes = 1; for (Ignite grid : G.allGrids()) { DistributedProcess<Integer, Integer> dp = new DistributedProcess<>(((IgniteEx)grid).context(), TEST_PROCESS, req -> GridTestUtils.runAsync(() -> { startLatch.countDown(); try { nodeLeftLatch.await(); } catch (InterruptedException ignored) { fail("Unexpected interrupt."); } return req; }), (uuid, res, err) -> { if (res.values().size() == NODES_CNT - 1 && res.values().stream().allMatch(i -> i == processRes)) finishLatch.countDown(); else fail("Unexpected process result [res=" + res + ", err=" + err + ']'); } ); processes.put(grid.name(), dp); } listeningLog.registerListener(s -> { if (s.startsWith("Failed to send a single message to coordinator")) msgSendLatch.countDown(); }); processes.get(grid(0).name()).start(UUID.randomUUID(), processRes); assertTrue(startLatch.await(TIMEOUT, MILLISECONDS)); stopGrid(0); assertTrue(finishLatch.await(TIMEOUT, MILLISECONDS)); assertFalse(failure.get()); }

Target:
public void testCoordinatorFailed() throws Exception { startGrids(NODES_CNT); CountDownLatch startLatch = new CountDownLatch(NODES_CNT); CountDownLatch finishLatch = new CountDownLatch(NODES_CNT - 1); HashMap<String, DistributedProcess<Integer, Integer>> processes = new HashMap<>(); int processRes = 1; for (Ignite grid : G.allGrids()) { DistributedProcess<Integer, Integer> dp = new DistributedProcess<>(((IgniteEx)grid).context(), TEST_PROCESS, req -> { IgniteInternalFuture<Integer> fut = runAsync(() -> { try { nodeLeftLatch.await(); } catch (InterruptedException ignored) { fail("Unexpected interrupt."); } return req; }); if (!grid.name().equals(getTestIgniteInstanceName(STOP_NODE_IDX))) fut.listen(f -> msgSendLatch.countDown()); startLatch.countDown(); return fut; }, (uuid, res, err) -> { if (res.values().size() == NODES_CNT - 1 && res.values().stream().allMatch(i -> i == processRes)) finishLatch.countDown(); else fail("Unexpected process result [res=" + res + ", err=" + err + ']'); } ); processes.put(grid.name(), dp); } processes.get(grid(STOP_NODE_IDX).name()).start(UUID.randomUUID(), processRes); assertTrue(startLatch.await(TIMEOUT, MILLISECONDS)); stopGrid(STOP_NODE_IDX); assertTrue(finishLatch.await(TIMEOUT, MILLISECONDS)); assertFalse(failure.get()); }
Source:
public AdvancedJUnitLaunchConfigurationDelegate() { allowAdvancedSourcelookup(); }

Target:
public AdvancedJUnitLaunchConfigurationDelegate() { super(); allowAdvancedSourcelookup(); }
Source:
protected void post2(BuildListener listener) throws Exception { if(getResult()== Result.SUCCESS) getStatus().onSuccessfulPromotion(Promotion.this); if (getTarget() != null) { getTarget().save(); } if (getResult() == Result.SUCCESS) { PromotedBuildAction pba = getTarget().getAction(PromotedBuildAction.class); for (PromotionProcess pp : pba.getPendingPromotions()) { pp.considerPromotion2(getTarget()); } for (AbstractProject<?,?> p : JenkinsHelper.getInstance().getAllItems(AbstractProject.class)) { PromotionTrigger pt = p.getTrigger(PromotionTrigger.class); if (pt!=null) pt.consider(Promotion.this); } } }

Target:
protected void post2(BuildListener listener) throws Exception { if (getTarget() == null) { listener.error("No Promotion target, cannot save target or update status"); return; } if(getResult()== Result.SUCCESS) getStatus().onSuccessfulPromotion(Promotion.this); getTarget().save(); if (getResult() == Result.SUCCESS) { PromotedBuildAction pba = getTarget().getAction(PromotedBuildAction.class); for (PromotionProcess pp : pba.getPendingPromotions()) { pp.considerPromotion2(getTarget()); } for (AbstractProject<?,?> p : JenkinsHelper.getInstance().getAllItems(AbstractProject.class)) { PromotionTrigger pt = p.getTrigger(PromotionTrigger.class); if (pt!=null) pt.consider(Promotion.this); } } }
Source:
public static EntityTypeSearchResults create(EntityType entityType, List<AttributeSearchResults> attributeSearchResults) { return new AutoValue_EntityTypeSearchResults(entityType, attributeSearchResults); }

Target:
public static EntityTypeSearchResults create(EntityType entityType, List<AttributeSearchResults> attributeSearchResults) { return new AutoValue_EntityTypeSearchResults(entityType, ImmutableList.copyOf(attributeSearchResults)); }
Source:
public final void postprocess() throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, ClassNotFoundException, IOException, CoreException { for (Field resultField : resultFields) { resultField.setAccessible(true); AbstractResult<?> result = (AbstractResult<?>) resultField.get(null); String name = NamingHelper.createFullNameForMember(resultField); result.setName(name); simulatorInitializationInfo.results.add(result); } for (Class<?> decisionPointClass : decisionPointClasses) { AbstractDecisionPoint dpt = (AbstractDecisionPoint) decisionPointClass.newInstance(); simulatorInitializationInfo.decisionPoints.add(dpt); } for (IResource processFile : BuildUtil.getAllFilesInProject(project, "proc")) { ProcessModelNode model; try { model = ProcessEditor.readModelFromFile((IFile) processFile); } catch (EOFException e) { continue; } List<Block> blocks; blocks = BlockConverter.convertModelToBlocks(model, modelContentsInfo); simulatorInitializationInfo.processBlocks.addAll(blocks); } for (Class<?> animationClass : animationClasses) { AnimationFrame frame = (AnimationFrame) animationClass.newInstance(); animationFrames.add(frame); } }

Target:
public final void postprocess() throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, ClassNotFoundException, IOException, CoreException { for (Field resultField : resultFields) { resultField.setAccessible(true); AbstractResult<?> result = (AbstractResult<?>) resultField.get(null); String name = NamingHelper.createFullNameForMember(resultField); result.setName(name); simulatorInitializationInfo.results.add(result); } for (Class<?> decisionPointClass : decisionPointClasses) { AbstractDecisionPoint dpt = (AbstractDecisionPoint) decisionPointClass.newInstance(); simulatorInitializationInfo.decisionPoints.add(dpt); } for (IResource processFile : BuildUtil.getAllFilesInProject(project, "proc")) { ProcessModelNode model = ProcessEditor.readModelFromFile((IFile) processFile); if (model == null) model = new ProcessModelNode(); List<Block> blocks = BlockConverter.convertModelToBlocks(model, modelContentsInfo); simulatorInitializationInfo.processBlocks.addAll(blocks); } for (Class<?> animationClass : animationClasses) { AnimationFrame frame = (AnimationFrame) animationClass.newInstance(); animationFrames.add(frame); } }
Source:
public void customApplicationIdUserAgentTest() throws Exception { final HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(new NoOpHttpClient() { @Override public Mono<HttpResponse> send(HttpRequest request) { String header = request.getHeaders().getValue("User-Agent"); String expectedHeaderPrefix = "user_specified_appId"; Assertions.assertTrue(header.startsWith(expectedHeaderPrefix)); return Mono.just(new MockHttpResponse(request, 200)); } }) .policies(new UserAgentPolicy( "user_specified_appId", "package.name", "package_version", Configuration.NONE, () -> "1.0")) .build(); HttpResponse response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http://localhost"))).block(); Assertions.assertEquals(200, response.getStatusCode()); }

Target:
public void customApplicationIdUserAgentTest() throws Exception { final String testSdkName = "sdk.name"; final String testAppId = "user_specified_appId"; final String testPackageVersion = "package_version"; String javaVersion = Configuration.getGlobalConfiguration().get("java.version"); String osName = Configuration.getGlobalConfiguration().get("os.name"); String osVersion = Configuration.getGlobalConfiguration().get("os.version"); String testPlatformInfo = javaVersion + "; " + osName + " " + osVersion; String expectedHeader = testAppId + " " + "azsdk-java-" + testSdkName + "/" + testPackageVersion + " " + testPlatformInfo; final HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(new NoOpHttpClient() { @Override public Mono<HttpResponse> send(HttpRequest request) { String header = request.getHeaders().getValue("User-Agent"); assertEquals(header, expectedHeader); return Mono.just(new MockHttpResponse(request, 200)); } }) .policies(new UserAgentPolicy( testAppId, testSdkName, testPackageVersion, Configuration.NONE, () -> "1.0")) .build(); Mono<HttpResponse> response = pipeline.send(new HttpRequest(HttpMethod.GET, new URL("http://localhost"))); StepVerifier.create(response) .expectNextMatches(httpResponse -> { assertEquals(200, httpResponse.getStatusCode()); assertEquals(expectedHeader, httpResponse.getRequest().getHeaders().getValue("User-Agent")); return true; }) .verifyComplete(); }
Source:
private synchronized void putConnectorConfig(String connName, final Map<String, String> config, boolean allowReplace, final Callback<Created<ConnectorInfo>> callback, ConfigInfos configInfos) { try { if (maybeAddConfigErrors(configInfos, callback)) { return; } final boolean created; if (configState.contains(connName)) { if (!allowReplace) { callback.onCompletion(new AlreadyExistsException("Connector " + connName + " already exists"), null); return; } worker.stopAndAwaitConnector(connName); created = false; } else { created = true; } configBackingStore.putConnectorConfig(connName, config); Callback<TargetState> onStart = new Callback<TargetState>() { @Override public void onCompletion(Throwable error, TargetState result) { if (error != null) { callback.onCompletion(error, null); return; } requestExecutorService.submit(new Runnable() { @Override public void run() { synchronized (this) { updateConnectorTasks(connName); } callback.onCompletion(null, new Created<>(created, createConnectorInfo(connName))); } }); } }; startConnector(connName, onStart); } catch (Throwable t) { callback.onCompletion(t, null); } }

Target:
private synchronized void putConnectorConfig(String connName, final Map<String, String> config, boolean allowReplace, final Callback<Created<ConnectorInfo>> callback, ConfigInfos configInfos) { try { if (maybeAddConfigErrors(configInfos, callback)) { return; } final boolean created; if (configState.contains(connName)) { if (!allowReplace) { callback.onCompletion(new AlreadyExistsException("Connector " + connName + " already exists"), null); return; } worker.stopAndAwaitConnector(connName); created = false; } else { created = true; } configBackingStore.putConnectorConfig(connName, config); startConnector(connName, (error, result) -> { if (error != null) { callback.onCompletion(error, null); return; } requestExecutorService.submit(() -> { updateConnectorTasks(connName); callback.onCompletion(null, new Created<>(created, createConnectorInfo(connName))); }); }); } catch (Throwable t) { callback.onCompletion(t, null); } }