auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ByteArrayInputStream uploadPackV2(String... inputLines) throws Exception { ByteArrayOutputStream send = new ByteArrayOutputStream(); PacketLineOut pckOut = new PacketLineOut(send); for (String line : inputLines) { if (line == PacketLineIn.END) { pckOut.end(); } else if (line == PacketLineIn.DELIM) { pckOut.writeDelim(); } else { pckOut.writeString(line); } } UploadPack up = new UploadPack(server); up.setUseProtocolV2(true); ByteArrayOutputStream recv = new ByteArrayOutputStream(); up.upload(new ByteArrayInputStream(send.toByteArray()), recv, null); ByteArrayInputStream recvStream = new ByteArrayInputStream(recv.toByteArray()); PacketLineIn pckIn = new PacketLineIn(recvStream); assertThat(pckIn.readString(), is("version 2")); assertThat(pckIn.readString(), is("ls-refs")); assertThat(pckIn.readString(), is("fetch=shallow")); assertTrue(pckIn.readString() == PacketLineIn.END); return recvStream; }

Target:
private ByteArrayInputStream uploadPackV2(String... inputLines) throws Exception { ByteArrayOutputStream send = new ByteArrayOutputStream(); PacketLineOut pckOut = new PacketLineOut(send); for (String line : inputLines) { if (line == PacketLineIn.END) { pckOut.end(); } else if (line == PacketLineIn.DELIM) { pckOut.writeDelim(); } else { pckOut.writeString(line); } } UploadPack up = new UploadPack(server); up.setUseProtocolV2(true); ByteArrayOutputStream recv = new ByteArrayOutputStream(); up.upload(new ByteArrayInputStream(send.toByteArray()), recv, null); ByteArrayInputStream recvStream = new ByteArrayInputStream(recv.toByteArray()); PacketLineIn pckIn = new PacketLineIn(recvStream); assertThat(pckIn.readString(), is("version 2")); assertThat( Arrays.asList(pckIn.readString(), pckIn.readString()), hasItems("ls-refs", "fetch=shallow")); assertTrue(pckIn.readString() == PacketLineIn.END); return recvStream; }
Source:
private void repaint() { if (graph != null) { System.out.println("repainting graph..."); Tile model = new Tile(graph); TileView view = new TileView(); TileController tc = new TileController(view, model); Group root = new Group(); wrapper.hvalueProperty().addListener( (ChangeListener<Number>) (ov, oldVal, newVal) -> { repaintPosition(tc, root, newVal.doubleValue()); }); Rectangle clip = new Rectangle(getMaxUnifiedEnd(graph) * VertexView.HORIZONTALSCALE, 0); root.getChildren().add(clip); repaintPosition(tc, root, wrapper.hvalueProperty().doubleValue()); } }

Target:
private void repaint() { if (graph != null) { GraphContainer model = new GraphContainer(graph); TileView view = new TileView(); TileController tileController = new TileController(view, model); Group root = new Group(); repaintPosition(tileController, root, wrapper.hvalueProperty() .doubleValue()); wrapper.hvalueProperty().addListener( (observable, oldValue, newValue) -> { repaintPosition(tileController, root, newValue.doubleValue()); }); Rectangle clip = new Rectangle(getMaxUnifiedEnd(graph) * VertexView.HORIZONTALSCALE, 0); root.getChildren().add(clip); repaintPosition(tileController, root, wrapper.hvalueProperty() .doubleValue()); } }
Source:
public Request iterate(final Request req, final Coordinates cords) { return null; }

Target:
public Request iterate(final Request req, final Coordinates cords) { throw new UnsupportedOperationException(); }
Source:
public MamQueryIQ parse(XmlPullParser parser, int initialDepth) throws Exception { String queryId = null; String node = null; DataForm dataForm = null; if (parser.getName().equals(MamQueryIQ.ELEMENT)) { queryId = parser.getAttributeValue("", "queryid"); node = parser.getAttributeValue("", "node"); boolean done = false; while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals(DataForm.ELEMENT)) { dataForm = new DataFormProvider().parse(parser); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals(MamQueryIQ.ELEMENT)) { done = true; } } } } return new MamQueryIQ(queryId, node, dataForm); }

Target:
public MamQueryIQ parse(XmlPullParser parser, int initialDepth) throws Exception { DataForm dataForm = null; String queryId = parser.getAttributeValue("", "queryid"); String node = parser.getAttributeValue("", "node"); outerloop: while (true) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals(DataForm.ELEMENT)) { dataForm = new DataFormProvider().parse(parser); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getDepth() == initialDepth) { break outerloop; } } } return new MamQueryIQ(queryId, node, dataForm); }
Source:
public static <T> TypeToken<T> getTypeToken(TypeToken<T> token, Class<? super T> raw) { if (raw!=null) return TypeToken.of((Class<T>)raw); if (token!=null) return token; throw new IllegalStateException("Both indicators of type are null"); }

Target:
public static <T> TypeToken<T> getTypeToken(TypeToken<T> token, Class<? super T> raw) { if (token!=null) return token; if (raw!=null) return TypeToken.of((Class<T>)raw); throw new IllegalStateException("Both indicators of type are null"); }
Source:
private void initPlugins() throws Exception { Collection<? extends InitStep> pluginsInitSteps = pluginLoader.getInitSteps(); for (InitStep initStep : pluginsInitSteps) { initStep.run(); } }

Target:
private void initPlugins() throws Exception { for (InitStep initStep : pluginLoader.getInitSteps()) { initStep.run(); } }
Source:
public <T> T cast(FormField<?> formField) { if (getDefaultOrNull(formField)) { return null; } if (this == formField.getValueType()) { return (T) formField.getValue(); } else if (STRING == formField.getValueType()) { return (T) formField.getValue().toString(); } else { throw LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format("Cannot cast from " + "field value of type %s to type %s", formField.getValueType(), PHONE_NUMBER))); } }

Target:
public <T> T cast(FormField<?> formField) { if (isFieldValueNull(formField)) { return null; } return (T) String.valueOf(formField.getValue()); }
Source:
public LengthFieldBasedFrameDecoder( ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) { checkPositive(maxFrameLength, "maxFrameLength"); checkPositiveOrZero(lengthFieldOffset, "lengthFieldOffset"); checkPositiveOrZero(initialBytesToStrip, "initialBytesToStrip"); if (lengthFieldOffset > maxFrameLength - lengthFieldLength) { throw new IllegalArgumentException( "maxFrameLength (" + maxFrameLength + ") " + "must be equal to or greater than " + "lengthFieldOffset (" + lengthFieldOffset + ") + " + "lengthFieldLength (" + lengthFieldLength + ")."); } this.byteOrder = checkNotNull(byteOrder, "byteOrder"); this.maxFrameLength = maxFrameLength; this.lengthFieldOffset = lengthFieldOffset; this.lengthFieldLength = lengthFieldLength; this.lengthAdjustment = lengthAdjustment; lengthFieldEndOffset = lengthFieldOffset + lengthFieldLength; this.initialBytesToStrip = initialBytesToStrip; this.failFast = failFast; }

Target:
public LengthFieldBasedFrameDecoder( ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) { this.byteOrder = checkNotNull(byteOrder, "byteOrder"); checkPositive(maxFrameLength, "maxFrameLength"); checkPositiveOrZero(lengthFieldOffset, "lengthFieldOffset"); checkPositiveOrZero(initialBytesToStrip, "initialBytesToStrip"); if (lengthFieldOffset > maxFrameLength - lengthFieldLength) { throw new IllegalArgumentException( "maxFrameLength (" + maxFrameLength + ") " + "must be equal to or greater than " + "lengthFieldOffset (" + lengthFieldOffset + ") + " + "lengthFieldLength (" + lengthFieldLength + ")."); } this.maxFrameLength = maxFrameLength; this.lengthFieldOffset = lengthFieldOffset; this.lengthFieldLength = lengthFieldLength; this.lengthAdjustment = lengthAdjustment; this.lengthFieldEndOffset = lengthFieldOffset + lengthFieldLength; this.initialBytesToStrip = initialBytesToStrip; this.failFast = failFast; }
Source:
public static Optional<TableRefAndRemainder> tryParseTableRef(LockDescriptor lockDescriptor) { byte[] rawBytes = lockDescriptor.getBytes(); int endOfTableName = Bytes.indexOf(rawBytes, (byte) 0); if (endOfTableName == -1) { return Optional.empty(); } String fullyQualifiedName = new String(rawBytes, 0, endOfTableName); TableReference tableRef = TableReference.createFromFullyQualifiedName(fullyQualifiedName); ByteString remainingBytes = ByteString.of(rawBytes, endOfTableName + 1, rawBytes.length - 1 - endOfTableName); return Optional.of(ImmutableTableRefAndRemainder.of(tableRef, remainingBytes)); }

Target:
public static Optional<TableRefAndRemainder> tryParseTableRef(LockDescriptor lockDescriptor) { byte[] rawBytes = lockDescriptor.getBytes(); int endOfTableName = Bytes.indexOf(rawBytes, (byte) 0); if (endOfTableName == -1) { return Optional.empty(); } String fullyQualifiedName = new String(rawBytes, 0, endOfTableName); TableReference tableRef = TableReference.createFromFullyQualifiedName(fullyQualifiedName); ByteString remainingBytes = ByteString.of(rawBytes, endOfTableName + 1, rawBytes.length - (endOfTableName + 1)); return Optional.of(ImmutableTableRefAndRemainder.of(tableRef, remainingBytes)); }
Source:
public void ThrottleForNormalizeTestWithinIdeal() throws Exception { List<RateLimit> scenarios = new ArrayList<>(); int limit = 5000; int buffer = ApiRateLimitChecker.calculateBuffer(limit); int approximateIdeal = 4000; scenarios.add(new RateLimit(limit, approximateIdeal + buffer - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 101, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 99, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 99, soon)); scenarios.add(new RateLimit(limit, limit, soon)); setupStubs(scenarios); ApiRateLimitChecker.ThrottleForNormalize.checkApiRateLimit(listener, github); assertEquals(1, countOfOutputLinesContaining("under budget")); assertFalse(handler.getView().stream().anyMatch(m -> m.getMessage().contains("Sleeping"))); ApiRateLimitChecker.ThrottleForNormalize.checkApiRateLimit(listener, github); assertEquals(2, countOfOutputLinesContaining("rechecking")); assertEquals(3, countOfOutputLinesContaining("Still sleeping")); assertEquals(2, countOfOutputLinesContaining("Sleeping for")); assertEquals(1, countOfOutputLinesContaining("under budget")); assertEquals(10, handler.getView().size()); }

Target:
public void ThrottleForNormalizeTestWithinIdeal() throws Exception { List<RateLimit> scenarios = new ArrayList<>(); int limit = 5000; int buffer = ApiRateLimitChecker.calculateBuffer(limit); int approximateIdeal = 4000; scenarios.add(new RateLimit(limit, approximateIdeal + buffer - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 101, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 100, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 99, soon)); scenarios.add(new RateLimit(limit, approximateIdeal - 99, soon)); scenarios.add(new RateLimit(limit, limit, soon)); setupStubs(scenarios); ApiRateLimitChecker.ThrottleForNormalize.checkApiRateLimit(listener, github); assertEquals(1, countOfOutputLinesContaining("under budget")); assertFalse(handler.getView().stream().anyMatch(m -> m.getMessage().contains("Sleeping"))); ApiRateLimitChecker.ThrottleForNormalize.checkApiRateLimit(listener, github); assertEquals(2, countOfOutputLinesContaining("rechecking")); assertEquals(3, countOfOutputLinesContaining("Still sleeping")); assertEquals(2, countOfOutputLinesContaining("Sleeping for")); assertEquals(1, countOfOutputLinesContaining("under budget")); assertEquals(2, countOfOutputLinesContaining("Jenkins is attempting to evenly distribute GitHub API requests")); assertEquals(10, handler.getView().size()); }
Source:
public boolean cleanupNode(final String id) { RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id); ResourceGroup resourceGroup = resourceGroupMap.getUnchecked(regionAndId.region()); String group = resourceGroup.name(); VirtualMachine virtualMachine = api.getVirtualMachineApi(group).get(regionAndId.id()); if (virtualMachine == null) { return true; } logger.debug(">> destroying %s ...", regionAndId.slashEncode()); boolean vmDeleted = deleteVirtualMachine(group, virtualMachine); cleanupVirtualMachineNICs(group, virtualMachine); cleanupVirtualMachineStorage(group, virtualMachine); return vmDeleted; }

Target:
public boolean cleanupNode(final String id) { RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id); ResourceGroup resourceGroup = resourceGroupMap.getUnchecked(regionAndId.region()); String resourceGroupName = resourceGroup.name(); VirtualMachine virtualMachine = api.getVirtualMachineApi(resourceGroupName).get(regionAndId.id()); if (virtualMachine == null) { return true; } logger.debug(">> destroying %s ...", regionAndId.slashEncode()); boolean vmDeleted = deleteVirtualMachine(resourceGroupName, virtualMachine); cleanupVirtualMachineNICs(resourceGroupName, virtualMachine); cleanupVirtualMachineStorage(resourceGroupName, virtualMachine); return vmDeleted; }
Source:
public Factory(long nowMillis, Request request, Response cacheResponse) { this.nowMillis = nowMillis; this.request = request; this.cacheResponse = cacheResponse; if (cacheResponse != null) { this.sentRequestMillis = cacheResponse.sentRequestAtMillis(); this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis(); Headers headers = cacheResponse.headers(); for (int i = 0, size = headers.size(); i < size; i++) { String fieldName = headers.name(i); String value = headers.value(i); if ("Date".equalsIgnoreCase(fieldName)) { servedDate = HttpDate.parse(value); servedDateString = value; } else if ("Expires".equalsIgnoreCase(fieldName)) { expires = HttpDate.parse(value); } else if ("Last-Modified".equalsIgnoreCase(fieldName)) { lastModified = HttpDate.parse(value); lastModifiedString = value; } else if ("ETag".equalsIgnoreCase(fieldName)) { etag = value; } else if ("Age".equalsIgnoreCase(fieldName)) { ageSeconds = UtilKtKt.toNonNegativeInt(value, -1); } } } }

Target:
public Factory(long nowMillis, Request request, Response cacheResponse) { this.nowMillis = nowMillis; this.request = request; this.cacheResponse = cacheResponse; if (cacheResponse != null) { this.sentRequestMillis = cacheResponse.sentRequestAtMillis(); this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis(); Headers headers = cacheResponse.headers(); for (int i = 0, size = headers.size(); i < size; i++) { String fieldName = headers.name(i); String value = headers.value(i); if ("Date".equalsIgnoreCase(fieldName)) { servedDate = HttpDate.parse(value); servedDateString = value; } else if ("Expires".equalsIgnoreCase(fieldName)) { expires = HttpDate.parse(value); } else if ("Last-Modified".equalsIgnoreCase(fieldName)) { lastModified = HttpDate.parse(value); lastModifiedString = value; } else if ("ETag".equalsIgnoreCase(fieldName)) { etag = value; } else if ("Age".equalsIgnoreCase(fieldName)) { ageSeconds = UtilKt.toNonNegativeInt(value, -1); } } } }
Source:
protected void doResolveAll(String inetHost, DnsRecord[] additionals, Promise<List<InetAddress>> promise, DnsCache resolveCache) throws Exception { if (inetHost == null || inetHost.isEmpty()) { promise.setSuccess(Collections.singletonList(loopbackAddress())); return; } final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost); if (bytes != null) { promise.setSuccess(Collections.singletonList(InetAddress.getByAddress(bytes))); return; } final String hostname = hostname(inetHost); InetAddress hostsFileEntry = resolveHostsFileEntry(hostname); if (hostsFileEntry != null) { promise.setSuccess(Collections.singletonList(hostsFileEntry)); return; } CacheResult res = doResolveAllCached(hostname, additionals, promise, resolveCache, resolvedInternetProtocolFamilies); if (res == CacheResult.CACHED) { return; } if (res == CacheResult.CACHED_EXPIRED) { promise = executor().newPromise(); } doResolveAllUncached(hostname, additionals, promise, promise, resolveCache, completeOncePreferredResolved); }

Target:
protected void doResolveAll(String inetHost, DnsRecord[] additionals, Promise<List<InetAddress>> promise, DnsCache resolveCache) throws Exception { if (inetHost == null || inetHost.isEmpty()) { promise.setSuccess(Collections.singletonList(loopbackAddress())); return; } final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost); if (bytes != null) { promise.setSuccess(Collections.singletonList(InetAddress.getByAddress(bytes))); return; } final String hostname = hostname(inetHost); InetAddress hostsFileEntry = resolveHostsFileEntry(hostname); if (hostsFileEntry != null) { promise.setSuccess(Collections.singletonList(hostsFileEntry)); return; } ResolvedAddresses result; result = doResolveAllCached(hostname, additionals, resolveCache, resolvedInternetProtocolFamilies); if (result != null) { if (result.cause() != null) { ResolvedAddresses secondaryResult = doResolveAllCached(hostname, additionals, resolveCacheFallback, resolvedInternetProtocolFamilies); if (secondaryResult != null && secondaryResult.cause() == null) { result = secondaryResult; } } result.complete(promise); return; } result = doResolveAllCached(hostname, additionals, resolveCacheFallback, resolvedInternetProtocolFamilies); if (result != null) { result.complete(promise); promise = executor().newPromise(); } doResolveAllUncached(hostname, additionals, promise, promise, resolveCache, resolveCacheFallback, completeOncePreferredResolved); }
Source:
private List<Resource> filterNotAuthorizedResource(PerunSession sess, List<Resource> resources) throws InternalErrorException { Iterator<Resource> resIterator = resources.iterator(); while(resIterator.hasNext()) { Resource resource = resIterator.next(); if(!AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN, resource) && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) resIterator.remove(); } return resources; }

Target:
private List<Resource> filterNotAuthorizedResource(PerunSession sess, List<Resource> resources) throws InternalErrorException { Iterator<Resource> resIterator = resources.iterator(); if (AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { return resources; } while(resIterator.hasNext()) { Resource resource = resIterator.next(); if(!AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN, resource)) resIterator.remove(); } return resources; }
Source:
public void initTrackerServers(List<TrackerServer> serverList) { serverList.add(new TrackerServer(new ServerBootstrap(), this.getName()) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1024, 1, 2, -3, 0)); pipeline.addLast("objectDecoder", new AstraProtocolDecoder(AstraProtocol.this)); } }); serverList.add(new TrackerServer(new ConnectionlessBootstrap(), this.getName()) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1024, 1, 2, -3, 0)); pipeline.addLast("objectDecoder", new AstraProtocolDecoder(AstraProtocol.this)); } }); }

Target:
public void initTrackerServers(List<TrackerServer> serverList) { serverList.add(new TrackerServer(new ServerBootstrap(), this.getName()) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1024, 1, 2, -3, 0)); pipeline.addLast("objectDecoder", new AstraProtocolDecoder(AstraProtocol.this)); } }); serverList.add(new TrackerServer(new ConnectionlessBootstrap(), this.getName()) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { pipeline.addLast("objectDecoder", new AstraProtocolDecoder(AstraProtocol.this)); } }); }
Source:
protected Properties getIntegrationProperties() { if (this.beanFactory != null) { return IntegrationContextUtils.getIntegrationProperties(this.beanFactory); } else { return null; } }

Target:
protected Properties getIntegrationProperties() { return IntegrationContextUtils.getIntegrationProperties(this.beanFactory); }
Source:
public void testShowStatsSelectNonStarFails() { assertQueryFails("SHOW STATS FOR (SELECT nationkey FROM nation_partitioned)", ".*Only SELECT \\* is supported in SHOW STATS SELECT clause"); }

Target:
public void testShowStatsSelectNonStarFails() { assertQueryFails("SHOW STATS FOR (SELECT orderkey FROM orders)", ".*Only SELECT \\* is supported in SHOW STATS SELECT clause"); assertQueryFails("SHOW STATS FOR (SELECT orderkey, custkey FROM orders)", ".*Only SELECT \\* is supported in SHOW STATS SELECT clause"); assertQueryFails("SHOW STATS FOR (SELECT *, * FROM orders)", ".*Only SELECT \\* is supported in SHOW STATS SELECT clause"); }
Source:
protected static ConnectionFactory getConnectionFactory( IDatabaseConnection databaseConnection, String url ) { ConnectionFactory factory = null; if ( url.startsWith( "jdbc:mysql:" ) || ( url.startsWith( "jdbc:mariadb:" ) ) ) { Properties props = new Properties(); props.put( "user", StringEscapeUtils.unescapeHtml( databaseConnection.getUsername() ) ); props.put( "password", StringEscapeUtils.unescapeHtml( databaseConnection.getPassword() ) ); props.put( "socketTimeout", "0" ); props.put( "connectTimeout", "5000" ); factory = new DriverManagerConnectionFactory( url, props ); } else { factory = new DriverManagerConnectionFactory( url, StringEscapeUtils.unescapeHtml( databaseConnection.getUsername() ), StringEscapeUtils.unescapeHtml( databaseConnection.getPassword() ) ); } return factory; }

Target:
protected static ConnectionFactory getConnectionFactory( IDatabaseConnection databaseConnection, String url ) { Properties props = new Properties(); props.put( "user", StringEscapeUtils.unescapeHtml( databaseConnection.getUsername() ) ); props.put( "password", StringEscapeUtils.unescapeHtml( databaseConnection.getPassword() ) ); if ( url.startsWith( "jdbc:mysql:" ) || ( url.startsWith( "jdbc:mariadb:" ) ) ) { props.put( "connectTimeout", "5000" ); } return new DriverManagerConnectionFactory( url, props ); }
Source:
public void testDisableIncrementalAnalysis() { executeTarget("testDisableIncrementalAnalysis"); assertOutputContaining("Avoid really long methods"); }

Target:
public void testDisableIncrementalAnalysis() { executeTarget("testDisableIncrementalAnalysis"); assertOutputContaining("Avoid really long methods"); assertDoesntContain(buildRule.getLog(), "This analysis could be faster"); assertFalse(currentTempFile().exists()); }
Source:
public void preInstall() { resolver = Entities.newDownloader(this); String subpath = entity.getConfig(BrooklynNode.SUBPATH_IN_ARCHIVE); if (subpath==null) { String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL); String origDownloadName = uploadUrl; if (origDownloadName==null) { String downloadUrlTemplate = entity.getAttribute(BrooklynNode.DOWNLOAD_URL); if (downloadUrlTemplate!=null) { origDownloadName = DownloadSubstituters.substitute(downloadUrlTemplate, DownloadSubstituters.getBasicEntitySubstitutions(this)); } } if (origDownloadName!=null) { origDownloadName = Urls.getBasename(origDownloadName); String downloadName = origDownloadName; downloadName = Strings.removeFromEnd(downloadName, ".tar.gz"); downloadName = Strings.removeFromEnd(downloadName, ".tgz"); downloadName = Strings.removeFromEnd(downloadName, ".zip"); if (!downloadName.equals(origDownloadName)) { downloadName = Strings.removeFromEnd(downloadName, "-dist"); subpath = downloadName; } } } if (subpath==null) subpath = format("brooklyn-%s", getVersion()); setExpandedInstallDir(Os.mergePaths(getInstallDir(), resolver.getUnpackedDirectoryName(subpath))); }

Target:
public void preInstall() { resolver = Entities.newDownloader(this); String subpath = entity.getConfig(BrooklynNode.SUBPATH_IN_ARCHIVE); if (subpath==null) { String uploadUrl = entity.getConfig(BrooklynNode.DISTRO_UPLOAD_URL); String origDownloadName = uploadUrl; if (origDownloadName==null) origDownloadName = entity.getAttribute(BrooklynNode.DOWNLOAD_URL); if (origDownloadName!=null) { origDownloadName = DownloadSubstituters.substitute(origDownloadName, DownloadSubstituters.getBasicEntitySubstitutions(this)); origDownloadName = Urls.decode(origDownloadName); origDownloadName = Urls.getBasename(origDownloadName); String downloadName = origDownloadName; downloadName = Strings.removeFromEnd(downloadName, ".tar.gz"); downloadName = Strings.removeFromEnd(downloadName, ".tgz"); downloadName = Strings.removeFromEnd(downloadName, ".zip"); if (!downloadName.equals(origDownloadName)) { downloadName = Strings.removeFromEnd(downloadName, "-dist"); subpath = downloadName; } } } if (subpath==null) subpath = format("brooklyn-%s", getVersion()); setExpandedInstallDir(Os.mergePaths(getInstallDir(), resolver.getUnpackedDirectoryName(subpath))); }
Source:
public boolean isLaunchedFromIntent() { return invokeSource.equals(InvokeSource.WIDGET) || invokeSource.equals(InvokeSource.INTENT_SHARE) || invokeSource.equals(InvokeSource.INTENT_PROCESS_TEXT); }

Target:
public boolean isLaunchedFromIntent() { return invokeSource.fromIntent(); }
Source:
private void initializeAsyncCancelAndVerifyCancelled(AlwaysFailingInitializer initializer, Runnable cleanupTask) throws InterruptedException { initializer.initialize(true); initializer.cancelInitialization(cleanupTask); int numberOfAttemptsWhenCancelled = initializer.initializationAttempts; initializer.deterministicScheduler.tick(ASYNC_INIT_DELAY * 5 + 1, TimeUnit.MILLISECONDS); assertThat(initializer.initializationAttempts).isEqualTo(numberOfAttemptsWhenCancelled); }

Target:
private void initializeAsyncCancelAndVerifyCancelled(AlwaysFailingInitializer initializer, Runnable cleanupTask) throws InterruptedException { initializer.initialize(true); initializer.cancelInitialization(cleanupTask); int numberOfAttemptsWhenCancelled = initializer.initializationAttempts; tickSchedulerFiveTimes(initializer); assertThat(initializer.initializationAttempts).isEqualTo(numberOfAttemptsWhenCancelled); }
Source:
public ExecutorService getExecutor(Properties p) { TypedProperties tp = TypedProperties.toTypedProperties(p); int maxThreads = tp.getIntProperty("maxThreads", 1); int queueSize = tp.getIntProperty("queueSize", 100000); long keepAliveTime = tp.getLongProperty("keepAlive", 10000); final int threadPrio = tp.getIntProperty("threadPriority", Thread.MIN_PRIORITY); final String threadNamePrefix = tp.getProperty("threadNamePrefix", tp.getProperty("componentName", "Thread")); final String threadNameSuffix = tp.getProperty("threadNameSuffix", ""); ThreadFactory tf = new ThreadFactory() { @Override public Thread newThread(Runnable r) { String threadName = threadNamePrefix + "-" + counter.getAndIncrement() + threadNameSuffix; Thread th = new Thread(r, threadName); th.setDaemon(true); th.setPriority(threadPrio); return th; } }; ThreadPoolExecutor tpe = new ThreadPoolExecutor(maxThreads, maxThreads, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(queueSize), tf, new ThreadPoolExecutor.CallerRunsPolicy()); tpe.allowCoreThreadTimeOut(true); return tpe; }

Target:
public ExecutorService getExecutor(Properties p) { TypedProperties tp = TypedProperties.toTypedProperties(p); int maxThreads = tp.getIntProperty("maxThreads", 1); int queueSize = tp.getIntProperty("queueSize", 100000); int coreThreads = queueSize == 0 ? 1 : tp.getIntProperty("coreThreads", maxThreads); long keepAliveTime = tp.getLongProperty("keepAliveTime", 60000); final int threadPrio = tp.getIntProperty("threadPriority", Thread.MIN_PRIORITY); final String threadNamePrefix = tp.getProperty("threadNamePrefix", tp.getProperty("componentName", "Thread")); final String threadNameSuffix = tp.getProperty("threadNameSuffix", ""); BlockingQueue<Runnable> queue = queueSize == 0 ? new SynchronousQueue<Runnable>() : new LinkedBlockingQueue<Runnable>(queueSize); ThreadFactory tf = new ThreadFactory() { @Override public Thread newThread(Runnable r) { String threadName = threadNamePrefix + "-" + counter.getAndIncrement() + threadNameSuffix; Thread th = new Thread(r, threadName); th.setDaemon(true); th.setPriority(threadPrio); return th; } }; return new ThreadPoolExecutor(coreThreads, maxThreads, keepAliveTime, TimeUnit.MILLISECONDS, queue, tf, new ThreadPoolExecutor.CallerRunsPolicy()); }
Source:
public GWCConfig getConfig() { if (gsEnvironment != null && gsEnvironment.isStale()) { syncEnvironment(); } return gwcConfigPersister.getConfig(); }

Target:
public GWCConfig getConfig() { return gwcConfigPersister.getConfig(); }
Source:
private void captureScreenshot(String comment, WebDriver driver, WebElement element, boolean errorMessage) { if (getMessage(errorMessage) != null) { comment = getMessage(errorMessage); } LOGGER.debug("DriverListener->captureScreenshot starting..."); try { if (errorMessage) { LOGGER.error(comment); Screenshot.captureFailure(driver, comment); } else { LOGGER.info(comment); if (MobileContextHelper.isInWebViewContext()) { MobileContextHelper.backUpContext(driver); Screenshot.capture(driver, comment); MobileContextHelper.restoreContext(driver); } else { Screenshot.capture(driver, comment); } } } catch (Exception e) { LOGGER.debug("Unrecognized failure detected in DriverListener->captureScreenshot: " + e.getMessage(), e); } finally { resetMessages(); } LOGGER.debug("DriverListener->captureScreenshot finished..."); }

Target:
private void captureScreenshot(String comment, WebDriver driver, WebElement element, boolean errorMessage) { if (getMessage(errorMessage) != null) { comment = getMessage(errorMessage); } LOGGER.debug("DriverListener->captureScreenshot starting..."); try { if (errorMessage) { LOGGER.error(comment); Screenshot.captureFailure(driver, comment); } else { LOGGER.info(comment); MobileContextHelper contextHelper = new MobileContextHelper(); if (contextHelper.isInWebViewContext(driver)) { String context = contextHelper.getContext(driver); contextHelper.changeToNativeAppContext(driver); Screenshot.capture(driver, comment); contextHelper.setContext(context, driver); } else { Screenshot.capture(driver, comment); } } } catch (Exception e) { LOGGER.debug("Unrecognized failure detected in DriverListener->captureScreenshot: " + e.getMessage(), e); } finally { resetMessages(); } LOGGER.debug("DriverListener->captureScreenshot finished..."); }
Source:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.my_courses, menu); final Config config = environment.getConfig(); if (config.isTabsLayoutEnabled()) { menu.findItem(R.id.menu_item_search).setVisible(false); menu.findItem(R.id.menu_item_account).setVisible(true); menu.findItem(R.id.menu_item_account).setIcon( new IconDrawable(getContext(), FontAwesomeIcons.fa_gear) .colorRes(getContext(), R.color.white) .actionBarSize(getContext())); } else { menu.findItem(R.id.menu_item_account).setVisible(false); if (config.getCourseDiscoveryConfig().isCourseDiscoveryEnabled()) { menu.findItem(R.id.menu_item_search).setVisible(true); } else { menu.findItem(R.id.menu_item_search).setVisible(false); } } }

Target:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.my_courses, menu); final Config config = environment.getConfig(); if (config.isTabsLayoutEnabled()) { menu.findItem(R.id.menu_item_search).setVisible(false); menu.findItem(R.id.menu_item_account).setVisible(true); menu.findItem(R.id.menu_item_account).setIcon( new IconDrawable(getContext(), FontAwesomeIcons.fa_gear) .colorRes(getContext(), R.color.white) .actionBarSize(getContext())); } else { menu.findItem(R.id.menu_item_account).setVisible(false); menu.findItem(R.id.menu_item_search).setVisible(config.getCourseDiscoveryConfig().isCourseDiscoveryEnabled()); } }
Source:
protected List<AttributeStatement> createSubjectRoleStatement(final CallbackProperties properties) throws SAMLAssertionBuilderException { final String userCode = properties.getUserCode(); final String userSystem = properties.getUserSystem(); final String userSystemName = properties.getUserSystemName(); final String userDisplay = properties.getUserDisplay(); if (Arrays.asList(userCode, userSystem, userSystemName, userDisplay).contains(null)) { LOG.error("No information provided to fill in user role attribute.."); throw new SAMLAssertionBuilderException("No information provided to fill in user role attribute."); } final List<AttributeStatement> statements = new ArrayList<>(); final List<Attribute> attributes = new ArrayList<>(); attributes.add(componentBuilder.createUserRoleAttribute(userCode, userSystem, userSystemName, userDisplay)); if (!attributes.isEmpty()) { statements.addAll(componentBuilder.createAttributeStatement(attributes)); } return statements; }

Target:
protected List<AttributeStatement> createSubjectRoleStatement(final CallbackProperties properties) { final String userCode = properties.getUserCode(); final String userSystem = properties.getUserSystem(); final String userSystemName = properties.getUserSystemName(); final String userDisplay = properties.getUserDisplay(); if (Arrays.asList(userCode, userSystem, userSystemName, userDisplay).contains(null)) { LOG.error("No information provided to fill in subject role attribute.."); throw new SAMLAssertionBuilderException("No information provided to fill in subject role attribute."); } final List<AttributeStatement> statements = new ArrayList<>(); final List<Attribute> attributes = new ArrayList<>(); attributes.add(componentBuilder.createSubjectRoleAttribute(userCode, userSystem, userSystemName, userDisplay)); if (!attributes.isEmpty()) { statements.addAll(componentBuilder.createAttributeStatement(attributes)); } return statements; }
Source:
public LineRanges within(final LineRanges ranges) { final LineRanges result = new LineRanges(); final Iterator<LineRange> iterator = ranges.iterate(); while (iterator.hasNext()) { final LineRange next = iterator.next(); for (final LineRange line : this.lines.collection()) { if (next.within(line)) { result.add(line); } } } return result; }

Target:
public LineRanges within(final LineRanges ranges) { final LineRanges result = new LineRanges(); final Iterator<LineRange> iterator = ranges.iterator(); while (iterator.hasNext()) { final LineRange next = iterator.next(); for (final LineRange line : this.lines.collection()) { if (next.within(line)) { result.add(line); } } } return result; }
Source:
public GlusterServersListReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); List<GlusterServerInfo> glusterServers = new ArrayList<GlusterServerInfo>(); 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])); } } setServer(glusterServers); }

Target:
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; }
Source:
private void buildTestedInstance() { ; this.tested = new ClientFullSessionImpl(factory, canvasCommandManager, sessionCommandManager, requestCommandManager, registryFactory); }

Target:
private void buildTestedInstance() { this.tested = new ClientFullSessionImpl(factory, canvasCommandManager, sessionCommandManager, requestCommandManager, registryFactory); }
Source:
public void parentIsNotCalledIfAccountStatusExceptionIsThrown() { AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException( "", new Throwable()) { }); AuthenticationManager parent = mock(AuthenticationManager.class); ProviderManager mgr = new ProviderManager( Collections.singletonList(iThrowAccountStatusException), parent); try { mgr.authenticate(mock(Authentication.class)); fail("Expected exception"); } catch (AccountStatusException expected) { } verifyZeroInteractions(parent); }

Target:
public void parentIsNotCalledIfAccountStatusExceptionIsThrown() { AuthenticationProvider iThrowAccountStatusException = createProviderWhichThrows(new AccountStatusException( "", new Throwable()) { }); AuthenticationManager parent = mock(AuthenticationManager.class); ProviderManager mgr = new ProviderManager( Collections.singletonList(iThrowAccountStatusException), parent); try { mgr.authenticate(mock(Authentication.class)); fail("Expected exception"); } catch (AccountStatusException expected) { } verifyNoInteractions(parent); }
Source:
private void initScanner(Schema projected) throws IOException { this.projector = new Projector(inSchema, outSchema, plan.getTargets()); System.out.println("=======================>" + plan.getTableDesc().getName()); for (FragmentProto f: fragments) { FileFragment ff = (FileFragment)FragmentConvertor.convert(context.getConf(), plan.getTableDesc().getMeta().getStoreType(), f); System.out.println(">>>>>>>>>>>>>>>>>>>" + ff.getPath()); } if (fragments != null) { if (fragments.length > 1) { this.scanner = new MergeScanner(context.getConf(), plan.getPhysicalSchema(), plan.getTableDesc().getMeta(), FragmentConvertor.<FileFragment>convert(context.getConf(), plan.getTableDesc().getMeta().getStoreType(), fragments), projected ); } else { this.scanner = StorageManagerFactory.getStorageManager( context.getConf()).getScanner(plan.getTableDesc().getMeta(), plan.getPhysicalSchema(), fragments[0], projected); } scanner.init(); } }

Target:
private void initScanner(Schema projected) throws IOException { this.projector = new Projector(inSchema, outSchema, plan.getTargets()); if (fragments != null) { if (fragments.length > 1) { this.scanner = new MergeScanner(context.getConf(), plan.getPhysicalSchema(), plan.getTableDesc().getMeta(), FragmentConvertor.<FileFragment>convert(context.getConf(), plan.getTableDesc().getMeta().getStoreType(), fragments), projected ); } else { this.scanner = StorageManagerFactory.getStorageManager( context.getConf()).getScanner(plan.getTableDesc().getMeta(), plan.getPhysicalSchema(), fragments[0], projected); } scanner.init(); } }
Source:
public boolean put(ConflictTxStream conflictStream) { Long val = cacheConflictKeys.get(conflictStream); if (val != null && val >= conflictStream.txVersion) { log.error("For key {}, the value is not smaller than the expected value or maxWildCard", conflictStream, cacheConflictKeys.get(conflictStream), conflictStream.txVersion, maxConflictWildcard); return false; } if (cacheConflictKeys.size() == cacheSize) { invalidateFirst(); } cacheEntries.add(conflictStream); cacheConflictKeys.put(conflictStream, conflictStream.txVersion); cacheEntriesBytes += conflictStream.size(); return true; }

Target:
public boolean put(ConflictTxStream conflictStream) { Long val = conflictKeys.getOrDefault(conflictStream, Address.NON_ADDRESS); if (val > conflictStream.txVersion) { log.error("For key the new entry address is smaller than the entry " + "address in cache. There is a sequencer regression.", conflictStream, conflictStream.txVersion, conflictKeys.get(conflictStream)); return false; } if (conflictKeys.size() == cacheSize) { invalidateSmallestTxVersion(); } cacheEntries.add(conflictStream); conflictKeys.put(conflictStream, conflictStream.txVersion); return true; }
Source:
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Collection<BindingSet> bindingSets) throws QueryEvaluationException { return null; }

Target:
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Collection<BindingSet> bindingSets) throws QueryEvaluationException { requireNonNull(bindingSets); final List<BindingSet> list = new ArrayList<>(); bindingSets.forEach(bindingSet -> { try { list.addAll(findBindings(bindingSet)); } catch (final Exception e) { Log.error("Unable to evaluate bindingset.", e); } }); return new CollectionIteration<>(list); }
Source:
public static <T> void handleBulkWriteError(List<BulkWriteError> errors,String op,GetCB cb) { for (BulkWriteError e : errors) { cb.getCtx(e.getIndex()).addError(getError(e,op)); } }

Target:
public static void handleBulkWriteError(List<BulkWriteError> errors,String op,GetCB cb) { for (BulkWriteError e : errors) { cb.getCtx(e.getIndex()).addError(getError(e,op)); } }
Source:
public Integer getPartition() { String changelogPartition = getMessageValue(CHANGELOG_VALUE_KEY); return (changelogPartition != null) ? Integer.parseInt(changelogPartition) : null; }

Target:
public Integer getPartition() { String changelogPartition = getMessageValue(CHANGELOG_VALUE_KEY); return StringUtils.isNotBlank(changelogPartition) ? Integer.parseInt(changelogPartition) : null; }
Source:
public void testInitAggregator() throws Exception { final List<BuiltinAggregator> aggregators = Arrays.asList(BuiltinAggregator.COUNT, BuiltinAggregator.MAX, BuiltinAggregator.MIN, BuiltinAggregator.SUM); testedView.initBuiltinAggregators(aggregators); aggregators.stream().forEach(agg -> verify(lstBuiltinAggregator).addOption(agg.value())); }

Target:
public void testInitAggregator() throws Exception { final List<BuiltinAggregator> aggregators = Arrays.asList(BuiltinAggregator.values()); testedView.initBuiltinAggregators(aggregators); aggregators.stream().forEach(agg -> verify(lstBuiltinAggregator).addOption(agg.value())); }
Source:
private void doCopyRetry(FileSystem sourceFs, List<ReplChangeManager.FileInfo> srcFileList, FileSystem destinationFs, Path destination, boolean useRegularCopy) throws IOException, LoginException { int repeat = 0; boolean isCopyError; List<Path> pathList = Lists.transform(srcFileList, ReplChangeManager.FileInfo::getEffectivePath); while (!pathList.isEmpty() && (repeat < MAX_COPY_RETRY)) { LOG.info("Attempt: " + (repeat+1) + ". Copying files: " + pathList); try { isCopyError = false; doCopyOnce(sourceFs, pathList, destinationFs, destination, useRegularCopy); } catch (IOException e) { if (!(e instanceof FileNotFoundException)) { LOG.info(" File operation failed with error : " + e.getMessage()); sourceFs = pathList.get(0).getFileSystem(hiveConf); destinationFs = destination.getFileSystem(hiveConf); } isCopyError = true; } pathList = getFilesToRetry(sourceFs, srcFileList, destinationFs, destination, isCopyError); repeat++; } if (!pathList.isEmpty()) { LOG.error("File copy failed even after several attempts. Files list: " + srcFileList); throw new IOException("File copy failed even after several attempts."); } }

Target:
private void doCopyRetry(FileSystem sourceFs, List<ReplChangeManager.FileInfo> srcFileList, FileSystem destinationFs, Path destination, boolean useRegularCopy) throws IOException, LoginException { int repeat = 0; boolean isCopyError = false; List<Path> pathList = Lists.transform(srcFileList, ReplChangeManager.FileInfo::getEffectivePath); while (!pathList.isEmpty() && (repeat < MAX_COPY_RETRY)) { try { if (repeat > 0) { pathList = getFilesToRetry(sourceFs, srcFileList, destinationFs, destination, isCopyError); if (pathList.isEmpty()) { break; } } LOG.info("Attempt: " + (repeat+1) + ". Copying files: " + pathList); isCopyError = true; doCopyOnce(sourceFs, pathList, destinationFs, destination, useRegularCopy); isCopyError = false; } catch (IOException e) { LOG.info("file operation failed", e); if (repeat >= (MAX_COPY_RETRY - 1)) { break; } if (!(e instanceof FileNotFoundException)) { int sleepTime = FileUtils.getSleepTime(repeat); LOG.info("Sleep for " + sleepTime + " milliseconds before retry " + (repeat+1)); try { Thread.sleep(sleepTime); } catch (InterruptedException timerEx) { LOG.info("sleep interrupted", timerEx.getMessage()); } FileSystem.closeAllForUGI(Utils.getUGI()); sourceFs = pathList.get(0).getFileSystem(hiveConf); destinationFs = destination.getFileSystem(hiveConf); } } repeat++; } if (!pathList.isEmpty()) { LOG.error("File copy failed even after several attempts. Files list: " + pathList); throw new IOException("File copy failed even after several attempts."); } }
Source:
public long forceNext() { long l = longs.incrementAndGet(INDEX_HEAD); if (((l >> 3) << 3) == l && concurrentInvocations() > 10) { concurrencyDetection.onDetected(); } return l; }

Target:
public long forceNext() { long l = longs.incrementAndGet(INDEX_HEAD); if (modPowerOfTwo(l, MOD) == 0 && concurrentInvocations() > MAX_CONCURRENT_CALLS) { concurrencyDetection.onDetected(); } return l; }
Source:
public boolean needsSequentialWriting() { return !vfsList.get(0).getCapabilities().contains(Capabilities.PARALLEL_WRITE); }

Target:
public boolean needsSequentialWriting() { return !capabilities.contains(Capabilities.PARALLEL_WRITE); }
Source:
private static NewIssueLocation locationForIssue(InputFile inputFile, HtmlIssue issue, NewIssue newIssue) { NewIssueLocation location = newIssue.newLocation() .on(inputFile) .message(issue.message()); Integer line = issue.line(); if (issue.startColumn() != null) { location.at(inputFile.newRange(issue.line(), issue.startColumn(), issue.endLine(), issue.endColumn())); } else if (line != null) { location.at(inputFile.selectLine(line)); } return location; }

Target:
private static NewIssueLocation locationForIssue(InputFile inputFile, HtmlIssue issue, NewIssue newIssue) { NewIssueLocation location = newIssue.newLocation() .on(inputFile) .message(issue.message()); Integer line = issue.line(); if (issue instanceof PreciseHtmlIssue) { PreciseHtmlIssue preciseHtmlIssue = (PreciseHtmlIssue) issue; location.at(inputFile.newRange(issue.line(), preciseHtmlIssue.startColumn(), preciseHtmlIssue.endLine(), preciseHtmlIssue.endColumn())); } else if (line != null) { location.at(inputFile.selectLine(line)); } return location; }
Source:
public FbChain(final Iterable<Fallback> fallbacks) { super( new Fallback() { @Override public Opt<Response> route(final RqFallback req) throws IOException { Opt<Response> rsp = new Opt.Empty<Response>(); for (final Fallback fbk : fallbacks) { final Opt<Response> opt = fbk.route(req); if (opt.has()) { rsp = new Opt.Single<Response>(opt.get()); break; } } return rsp; } } ); }

Target:
public FbChain(final Iterable<Fallback> fallbacks) { super( new Fallback() { @Override public Opt<Response> route(final RqFallback req) throws IOException { Opt<Response> rsp = new Opt.Empty<Response>(); for (final Fallback fbk : fallbacks) { final Opt<Response> opt = fbk.route(req); if (opt.has()) { rsp = opt; break; } } return rsp; } } ); }
Source:
protected void executeCommand() { final List<LUNs> lunsFromVgInfo = (List<LUNs>) runVdsCommand(VDSCommandType.GetVGInfo, new GetVGInfoVDSCommandParameters(getVds().getId(), getStorageDomain().getStorage())).getReturnValue(); final List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); Map<Consumer<List<LUNs>>, List<LUNs>> lunsToUpdateInDb = getLunsToUpdateInDb(lunsFromVgInfo, lunsFromDb); Boolean dbShouldBeUpdated = lunsToUpdateInDb.containsKey(updateExistingLuns) || lunsToUpdateInDb.containsKey(saveNewLuns); if (dbShouldBeUpdated) { TransactionSupport.executeInNewTransaction(() -> { updateLunsInDb(lunsToUpdateInDb); refreshLunsConnections(lunsFromVgInfo); cleanupLunsFromDb(lunsFromVgInfo, lunsFromDb); return null; }); } setSucceeded(true); }

Target:
protected void executeCommand() { final List<LUNs> lunsFromVgInfo = (List<LUNs>) runVdsCommand(VDSCommandType.GetVGInfo, new GetVGInfoVDSCommandParameters(getVds().getId(), getStorageDomain().getStorage())).getReturnValue(); final List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); Map<Consumer<List<LUNs>>, List<LUNs>> lunsToUpdateInDb = getLunsToUpdateInDb(lunsFromVgInfo, lunsFromDb); boolean dbShouldBeUpdated = lunsToUpdateInDb.containsKey(updateExistingLuns) || lunsToUpdateInDb.containsKey(saveNewLuns); if (dbShouldBeUpdated) { TransactionSupport.executeInNewTransaction(() -> { updateLunsInDb(lunsToUpdateInDb); refreshLunsConnections(lunsFromVgInfo); cleanupLunsFromDb(lunsFromVgInfo, lunsFromDb); return null; }); } setSucceeded(true); }