auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String getHostId() { CTFClock clock = getCTFTrace().getClock(); if (clock != null) { return (String) clock.getProperty(CLOCK_HOST_PROPERTY); } return getName(); }

Target:
public String getHostId() { CTFClock clock = getCTFTrace().getClock(); if (clock != null) { return (String) clock.getProperty(CLOCK_HOST_PROPERTY); } return super.getHostId(); }
Source:
public String getKey() { StringBuffer sb = new StringBuffer(); sb.append(this.user.getUserId()); sb.append("_").append(this.language.getId()); if (StringUtils.isNotBlank(this.queryString)) { sb.append("_").append(this.queryString); } if (UtilMethods.isSet(persona) && StringUtils.isNotBlank(this.persona.getKeyTag())) { sb.append("_").append(this.persona); } return sb.toString(); }

Target:
public String getKey() { StringBuilder sb = new StringBuilder(); sb.append(this.user.getUserId()); sb.append(StringPool.UNDERLINE).append(this.language.getId()); if (StringUtils.isNotBlank(this.queryString)) { sb.append(StringPool.UNDERLINE).append(this.queryString); } if (UtilMethods.isSet(persona) && StringUtils.isNotBlank(this.persona.getKeyTag())) { sb.append(StringPool.UNDERLINE).append(this.persona); } return sb.toString(); }
Source:
static public Drive getDriveService(String token) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setHttpRequestInitializer(new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { credential.initialize(httpRequest); httpRequest.setConnectTimeout(300 * 60000); httpRequest.setReadTimeout(300 * 60000); } }) .setApplicationName(SERVICE_APP_NAME).build(); }

Target:
static public Drive getDriveService(String token) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setHttpRequestInitializer(new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { credential.initialize(httpRequest); httpRequest.setConnectTimeout(3 * 60000); httpRequest.setReadTimeout(3 * 60000); } }) .setApplicationName(SERVICE_APP_NAME).build(); }
Source:
public void testFingerprintUmd() { testModules( "test.js", lines( "(function (name, context, definition) {", " 'use strict';", " if (typeof define === 'function' && define.amd) {", " define(definition);", " } else if (typeof module !== 'undefined' && module.exports) {", " module.exports = definition();", " } else if (context.exports) {", " context.exports = definition();", " } else {", " context[name] = definition();", " }", "})('Fingerprint2', this, function() {", " var Fingerprint2 = function() {", " if (!(this instanceof Fingerprint2)) { return new Fingerprint2(); }", " };", " return Fingerprint2$$module$test;", "})"), lines( " var module$test = {};", "var Fingerprint2$$module$test = function() {", " if (!(this instanceof Fingerprint2$$module$test)) {", " return new Fingerprint2$$module$test();", " }", "};", "module$test.default = Fingerprint2$$module$test;")); }

Target:
public void testFingerprintUmd() { testModules( "test.js", lines( "(function (name, context, definition) {", " 'use strict';", " if (typeof define === 'function' && define.amd) {", " define(definition);", " } else if (typeof module !== 'undefined' && module.exports) {", " module.exports = definition();", " } else if (context.exports) {", " context.exports = definition();", " } else {", " context[name] = definition();", " }", "})('Fingerprint2', this, function() {", " var Fingerprint2 = function() {", " if (!(this instanceof Fingerprint2)) { return new Fingerprint2(); }", " };", " return Fingerprint2;", "})"), lines( " var module$test = {};", "var Fingerprint2$$module$test = function() {", " if (!(this instanceof Fingerprint2$$module$test)) {", " return new Fingerprint2$$module$test();", " }", "};", "module$test.default = Fingerprint2$$module$test;")); }
Source:
public TpcdsDataSource(TpcdsTable table, int scaleFactor) { this.table = table; this.scaleFactor = scaleFactor; }

Target:
public TpcdsDataSource(TpcdsTable table, int scaleFactor) { checkArgument(scaleFactor > 0, "Scale factor should be greater than 0: %s", scaleFactor); this.table = table; this.scaleFactor = scaleFactor; }
Source:
private final List<String> managedPathsWithFiles(Configuration config, DeploymentType deployment) { ImmutableList.Builder<String> nonEmptyPaths = ImmutableList.builder(); if (!config.m_isEnterprise) { return nonEmptyPaths.build(); } PathsType paths = deployment.getPaths(); String voltDbRoot = paths.getVoltdbroot().getPath(); String path; if ((path = managedPathEmptyCheck(voltDbRoot, paths.getSnapshots().getNodePath())) != null) nonEmptyPaths.add(path); if ((path = managedPathEmptyCheck(voltDbRoot, paths.getExportoverflow().getNodePath())) != null) nonEmptyPaths.add(path); if ((path = managedPathEmptyCheck(voltDbRoot, paths.getDroverflow().getNodePath())) != null) nonEmptyPaths.add(path); if ((path = managedPathEmptyCheck(voltDbRoot, paths.getCommandlog().getNodePath())) != null) nonEmptyPaths.add(path); if ((path = managedPathEmptyCheck(voltDbRoot, paths.getCommandlogsnapshot().getNodePath())) != null) nonEmptyPaths.add(path); return nonEmptyPaths.build(); }

Target:
private List<String> managedPathsWithFiles(Configuration config, DeploymentType deployment) { ImmutableList.Builder<String> nonEmptyPaths = ImmutableList.builder(); if (!config.m_isEnterprise) { return nonEmptyPaths.build(); } PathsType paths = deployment.getPaths(); String voltDbRoot = getVoltDBRootPath(paths.getVoltdbroot()); String path; if ((path = managedPathEmptyCheck(voltDbRoot, getSnapshotPath(paths.getSnapshots()))) != null) nonEmptyPaths.add(path); if ((path = managedPathEmptyCheck(voltDbRoot, getExportOverflowPath(paths.getExportoverflow()))) != null) nonEmptyPaths.add(path); if ((path = managedPathEmptyCheck(voltDbRoot, getDROverflowPath(paths.getDroverflow()))) != null) nonEmptyPaths.add(path); if ((path = managedPathEmptyCheck(voltDbRoot, getCommandLogPath(paths.getCommandlog()))) != null) nonEmptyPaths.add(path); if ((path = managedPathEmptyCheck(voltDbRoot, getCommandLogSnapshotPath(paths.getCommandlogsnapshot()))) != null) nonEmptyPaths.add(path); return nonEmptyPaths.build(); }
Source:
public String getIdentifierForSeed(long seed) { int seqLength = firstIdentifierBase == null ? 1 : firstIdentifierBase.length(); String identifier = IdgenUtil.convertToBase(seed, baseCharacterSet.toCharArray(), seqLength); PrefixProvider prefixProvider = getPrefixProvider(prefix); if (prefixProvider != null) { identifier = (prefix == null ? identifier : prefixProvider.getValue() + identifier); } else { identifier = (prefix == null ? identifier : prefix + identifier); } identifier = (suffix == null ? identifier : identifier + suffix); if (getIdentifierType() != null && StringUtils.isNotEmpty(getIdentifierType().getValidator())) { try { Class<?> c = Context.loadClass(getIdentifierType().getValidator()); IdentifierValidator v = (IdentifierValidator)c.newInstance(); identifier = v.getValidIdentifier(identifier); } catch (Exception e) { throw new RuntimeException("Error generating check digit with " + getIdentifierType().getValidator(), e); } } if (this.minLength != null && this.minLength > 0) { if (identifier.length() < this.minLength) { throw new RuntimeException("Invalid configuration for IdentifierSource. Length minimum set to " + this.minLength + " but generated " + identifier); } } if (this.maxLength != null && this.maxLength > 0) { if (identifier.length() > this.maxLength) { throw new RuntimeException("Invalid configuration for IdentifierSource. Length maximum set to " + this.maxLength + " but generated " + identifier); } } return identifier; }

Target:
public String getIdentifierForSeed(long seed) { int seqLength = firstIdentifierBase == null ? 1 : firstIdentifierBase.length(); String identifier = IdgenUtil.convertToBase(seed, baseCharacterSet.toCharArray(), seqLength); PrefixProvider prefixProvider = getPrefixProvider(prefix); if (prefixProvider == null) { prefixProvider = new ConstantPrefixProvider(prefix); } identifier = prefixProvider.getValue() + identifier; identifier = (suffix == null ? identifier : identifier + suffix); if (getIdentifierType() != null && StringUtils.isNotEmpty(getIdentifierType().getValidator())) { try { Class<?> c = Context.loadClass(getIdentifierType().getValidator()); IdentifierValidator v = (IdentifierValidator)c.newInstance(); identifier = v.getValidIdentifier(identifier); } catch (Exception e) { throw new RuntimeException("Error generating check digit with " + getIdentifierType().getValidator(), e); } } if (this.minLength != null && this.minLength > 0) { if (identifier.length() < this.minLength) { throw new RuntimeException("Invalid configuration for IdentifierSource. Length minimum set to " + this.minLength + " but generated " + identifier); } } if (this.maxLength != null && this.maxLength > 0) { if (identifier.length() > this.maxLength) { throw new RuntimeException("Invalid configuration for IdentifierSource. Length maximum set to " + this.maxLength + " but generated " + identifier); } } return identifier; }
Source:
public static void e(String tag, String message) { SalesforceLogger.getLogger(COMPONENT_NAME, SmartStoreSDKManager.getInstance().getAppContext()).e( tag, message); }

Target:
public static void e(String tag, String message) { getLogger().e(tag, message); }
Source:
public List<BinaryContent> transform( List<Metacard> metacards, MimeType mimeType, String transformerId, Map<String, Serializable> transformerArguments) throws CatalogTransformerException { if (CollectionUtils.isEmpty(metacards)) { throw new IllegalArgumentException("Metacards list is empty."); } List<MultiMetacardTransformer> multiMetacardTransformers = StringUtils.isNotEmpty(transformerId) ? transformerLocator.findMultiMetacardTransformers(transformerId) : transformerLocator.findMultiMetacardTransformers(mimeType); LOGGER.trace( "List of matches for mimeType and transformerId [{}]: {}", mimeType, transformerId, multiMetacardTransformers); if (CollectionUtils.isEmpty(multiMetacardTransformers)) { throw new IllegalArgumentException("Transformer " + transformerId + " not found"); } List<String> stackTraceList = new ArrayList<>(); List<BinaryContent> binaryContents = null; for (MultiMetacardTransformer transformer : multiMetacardTransformers) { try { binaryContents = transformer.transform(metacards, transformerArguments); } catch (CatalogTransformerException e) { List<String> stackTraces = Arrays.asList(ExceptionUtils.getRootCauseStackTrace(e)); stackTraceList.add( String.format("Transformer [%s] could not transform metacard.", transformer)); stackTraceList.addAll(stackTraces); LOGGER.debug("Transformer could not transform metacard.", transformer, e); } } if (CollectionUtils.isEmpty(binaryContents)) { throw new CatalogTransformerException( String.format( "Could not transform metacards: transformerId=%s : %s", transformerId, StringUtils.join(stackTraceList, "\n"))); } return binaryContents; }

Target:
public List<BinaryContent> transform( List<Metacard> metacards, MimeType mimeType, String transformerId, Map<String, Serializable> transformerArguments) throws CatalogTransformerException { if (CollectionUtils.isEmpty(metacards)) { throw new IllegalArgumentException("Metacards list is empty."); } List<MultiMetacardTransformer> multiMetacardTransformers = StringUtils.isNotEmpty(transformerId) ? transformerLocator.findMultiMetacardTransformers(transformerId) : transformerLocator.findMultiMetacardTransformers(mimeType); LOGGER.trace( "List of matches for mimeType and transformerId [{}]: {}", mimeType, transformerId, multiMetacardTransformers); if (CollectionUtils.isEmpty(multiMetacardTransformers)) { throw new IllegalArgumentException( String.format( "Transformer not found for transformerId=%s or mime-type=%s.", getSafeTransformerId(transformerId), mimeType)); } List<String> stackTraceList = new ArrayList<>(); List<BinaryContent> binaryContents = null; for (MultiMetacardTransformer transformer : multiMetacardTransformers) { binaryContents = attemptTransform(metacards, transformerArguments, stackTraceList, transformer); if (CollectionUtils.isNotEmpty(binaryContents)) { break; } } if (CollectionUtils.isEmpty(binaryContents)) { throw new CatalogTransformerException( String.format( "Could not transform metacards: transformerId=%s : %s", getSafeTransformerId(transformerId), StringUtils.join(stackTraceList, "\n"))); } return binaryContents; }
Source:
public void getGapsFromNonNormalizedTracker() { tracker.addRange(500, 999); for (Pair<Long, Long> gap = tracker.getFirstGap(1); gap != null; gap = tracker .getFirstGap(gap.getSecond() + 1)) }

Target:
public void getGapsFromNonNormalizedTracker() { tracker.addRange(500, 999); assertEquals(Pair.of(ExportSequenceNumberTracker.MIN_SEQNO, 499L), tracker.getFirstGap(1)); assertEquals(Pair.of(1000L, ExportSequenceNumberTracker.INFINITE_SEQNO), tracker.getFirstGap(500)); assertNull(tracker.getFirstGap(ExportSequenceNumberTracker.INFINITE_SEQNO + 1)); }
Source:
public Team getTeam(EntityPlayer player) { String username = player.getName(); for(Team team : teams) { for (String name : team.members) { if (username.equals(name)) { return team; } } } return null; }

Target:
public Optional<Team> getTeam(EntityPlayer player) { String username = player.getName(); for(Team team : teams) { for (String name : team.members) { if (username.equals(name)) { return Optional.of(team); } } } return Optional.empty(); }
Source:
public void update(final VDS host) { try { AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hostnames(host.getHostName()) .verboseLevel(AnsibleVerbosity.LEVEL1) .logFileDirectory(VdsDeployBase.HOST_DEPLOY_LOG_DIRECTORY) .logFilePrefix("ovirt-host-mgmt-ansible") .logFileName(host.getHostName()) .logFileSuffix(CorrelationIdTracker.getCorrelationId()) .playbook(AnsibleConstants.HOST_UPGRADE_PLAYBOOK); if (ansibleExecutor.runCommand(command).getAnsibleReturnCode() != AnsibleReturnCode.OK) { log.error("Failed to update host '{}'.", host.getName()); throw new RuntimeException("Failed to update host '{}'."); } } catch (InterruptedException | IOException ex) { throw new RuntimeException(ex); } }

Target:
public void update(final VDS host) { try { AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hostnames(host.getHostName()) .verboseLevel(AnsibleVerbosity.LEVEL1) .logFileDirectory(VdsDeployBase.HOST_DEPLOY_LOG_DIRECTORY) .logFilePrefix("ovirt-host-mgmt-ansible") .logFileName(host.getHostName()) .logFileSuffix(CorrelationIdTracker.getCorrelationId()) .playbook(AnsibleConstants.HOST_UPGRADE_PLAYBOOK); if (ansibleExecutor.runCommand(command).getAnsibleReturnCode() != AnsibleReturnCode.OK) { String error = String.format("Failed to update host '%1$s'.", host.getHostName()); log.error(error); throw new RuntimeException(error); } } catch (InterruptedException | IOException ex) { throw new RuntimeException(ex); } }
Source:
private boolean matchesFilter(StackTraceElement[] stackTraces) { for (StackTraceElement element : stackTraces) { String methodName = element.getMethodName(); String className = element.getClassName(); int low = 0; int high = filters.length; while (low < high) { int mid = (low + high) >>> 1; Filter filter = filters[mid]; int c = methodName.compareTo(filter.methodName); if (c == 0) c = className.compareTo(filter.className); if (c == 0) { return true; } else if (c < 0) { high = mid; } else { low = mid + 1; } } } return false; }

Target:
private boolean matchesFilter(StackTraceElement[] stackTraces) { for (StackTraceElement element : stackTraces) { String methodName = element.getMethodName(); String className = element.getClassName(); int low = 0; int high = filters.length; while (low < high) { int mid = (low + high) >>> 1; Filter filter = filters[mid]; int c = methodName.compareTo(filter.methodName); if (c == 0) { c = className.compareTo(filter.className); } if (c == 0) { return true; } else if (c < 0) { high = mid; } else { low = mid + 1; } } } return false; }
Source:
protected void checkFieldType(Type type, Object value) throws OperationException { if (!type.isListType()) { throw new OperationException("Only multivalued types can be set using this operation"); } ListType listType = (ListType) type; Type itemType = listType.getFieldType(); if (itemType.isComplexType()) { throw new UnsupportedOperationException("Manage only lists of scalar items"); } String exceptionReason = String.format("Given type \"%s\" value is not a %s type", value, itemType.getName()); try { if (itemType.convert(value) == null) { throw new UnsupportedOperationException(exceptionReason); } } catch (TypeException | ClassCastException e) { throw new OperationException(exceptionReason, e); } }

Target:
protected void checkFieldType(Type type, Object value) throws OperationException { if (!type.isListType()) { throw new OperationException("Only multivalued types can be set using this operation"); } ListType listType = (ListType) type; Type itemType = listType.getFieldType(); if (itemType.isComplexType()) { throw new UnsupportedOperationException("Manage only lists of scalar items"); } try { if (itemType.convert(value) == null) { String exceptionReason = String.format("Given type \"%s\" value is not a %s type", value, itemType.getName()); throw new UnsupportedOperationException(exceptionReason); } } catch (TypeException | ClassCastException e) { String exceptionReason = String.format("Given type \"%s\" value is not a %s type", value, itemType.getName()); throw new OperationException(exceptionReason, e); } }
Source:
public void floorTest() throws DatabaseEngineException { test5Columns(); EntityEntry.Builder entry = entry() .set("COL1", 2) .set("COL2", false) .set("COL3", 2.5D) .set("COL4", 3L) .set("COL5", "ADEUS"); for (int i = 0; i < 10; i++) { entry.set("COL1", i); engine.persist("TEST", entry .build()); } List<Map<String, ResultColumn>> query = engine.query(select(floor(column("COL3")).alias("FLOOR")).from(table("TEST"))); assertEquals("result ok?", 2.0, query.get(0).get("FLOOR").toDouble(), 0.1); }

Target:
public void floorTest() throws DatabaseEngineException { test5Columns(); EntityEntry.Builder entry = entry() .set("COL1", 2) .set("COL2", false) .set("COL3", 2.5D) .set("COL4", 3L) .set("COL5", "ADEUS"); for (int i = 0; i < 10; i++) { entry.set("COL1", i); engine.persist("TEST", entry .build()); } List<Map<String, ResultColumn>> query = engine.query(select(floor(column("COL3")).alias("FLOOR")).from(table("TEST"))); assertEquals("result ok?", 2.0, query.get(0).get("FLOOR").toDouble(), DELTA); }
Source:
public final void testConsumerTransitionsToProcessingWithIntermittentInitializationFailures() { ExecutorService failingService = spy(executorService); ShardConsumer consumer = new ShardConsumer(recordsPublisher, failingService, shardInfo, logWarningForTaskAfterMillis, shardConsumerArgument, blockedOnParentsState, t -> t, 1, taskExecutionListener, 0); mockSuccessfulUnblockOnParents(); mockSuccessfulInitializeWithFailureTransition(); mockSuccessfulProcessing(null); doAnswer(invocation -> directlyExecuteRunnable(invocation)) .doThrow(new RejectedExecutionException()) .doThrow(new RejectedExecutionException()) .doThrow(new RejectedExecutionException()) .doAnswer(invocation -> directlyExecuteRunnable(invocation)) .when(failingService).execute(any()); int arbitraryExecutionCount = 6; do { try { consumer.executeLifecycle(); } catch (Exception e) { } } while (--arbitraryExecutionCount > 0); assertEquals(ShardConsumerState.PROCESSING.consumerState().state(), consumer.currentState().state()); verify(failingService, times(5)).execute(any()); }

Target:
public final void testConsumerTransitionsToProcessingWithIntermittentInitializationFailures() { ExecutorService failingService = spy(executorService); ShardConsumer consumer = new ShardConsumer(recordsPublisher, failingService, shardInfo, logWarningForTaskAfterMillis, shardConsumerArgument, blockedOnParentsState, t -> t, 1, taskExecutionListener, 0); mockSuccessfulUnblockOnParents(); mockSuccessfulInitializeWithFailureTransition(); mockSuccessfulProcessing(null); doAnswer(invocation -> directlyExecuteRunnable(invocation)) .doThrow(new RejectedExecutionException()) .doThrow(new RejectedExecutionException()) .doThrow(new RejectedExecutionException()) .doAnswer(invocation -> directlyExecuteRunnable(invocation)) .when(failingService).execute(any()); int arbitraryExecutionCount = 6; do { try { consumer.executeLifecycle(); } catch (Exception e) { fail("Unexpected exception while executing consumer lifecycle"); } } while (--arbitraryExecutionCount > 0); assertEquals(ShardConsumerState.PROCESSING.consumerState().state(), consumer.currentState().state()); verify(failingService, times(5)).execute(any()); }
Source:
public void setMaxWait(int num) { blockingTimeoutMillis = num; log.warn( "maxWait deprecated dbcp pool attribute usage, should use blockingTimeoutMillis geronimo pool attribute instead"); }

Target:
public void setMaxWait(int num) { blockingTimeoutMillis = num; }
Source:
private void assertCorrectMetacardsReturned( List<Result> results, int startIndex, int expectedNumberOfMetacards) { assertThat(results.size(), is(expectedNumberOfMetacards)); for (int i = 0; i < expectedNumberOfMetacards; i++) { int id = startIndex + i; assertThat(results.get(i).getMetacard().getId(), equalTo("ID_" + String.valueOf(id))); } }

Target:
private void assertCorrectMetacardsReturned( List<Result> results, int startIndex, int expectedNumberOfMetacards) { assertThat(results, hasSize(expectedNumberOfMetacards)); for (int i = 0; i < expectedNumberOfMetacards; i++) { int id = startIndex + i; assertThat(results.get(i).getMetacard().getId(), equalTo("ID_" + String.valueOf(id))); } }
Source:
public void cannotDeleteClientByUnauthorizedUsers() { makeUnauthorizedOperationAndVerify(getClientPath("any-client"), RequestType.DELETE, null); }

Target:
public void cannotDeleteClientByUnauthorizedUsers() { makeUnauthorizedOperationAndVerify(getClientPath(TEST_CLIENT_3), RequestType.DELETE, null); }
Source:
private void handleIOException(IOExceptionWithStatus ioe) throws IOException { Status.Code code = ioe.getStatus().getCode(); if (retryOptions.isRetryable(code)) { logger.info("Reissuing scan after receiving error with status: %s.", code.name()); if (currentErrorBackoff == null) { currentErrorBackoff = retryOptions.createBackoff(); } backOffAndRetry(currentErrorBackoff, ioe); } else { throw ioe; } }

Target:
private void handleIOException(IOExceptionWithStatus ioe) throws IOException { Status.Code code = ioe.getStatus().getCode(); if (retryOptions.isRetryable(code)) { logger.info("Reissuing scan after receiving error with status: %s.", code.name()); if (currentErrorBackoff == null) { currentErrorBackoff = retryOptions.createBackoff(); } long nextBackOffMillis = currentErrorBackoff.nextBackOffMillis(); if (nextBackOffMillis == BackOff.STOP) { throw new BigtableRetriesExhaustedException("Exhausted streaming retries.", ioe); } sleep(nextBackOffMillis); reissueRequest(); } else { throw ioe; } }
Source:
public Object getService(String serviceName) { synchronized (agentServices) { checkRunning(); Object service = agentServices.get(serviceName); if (service != null) return service; PriorityQueue<ServiceReference<IAgentServiceFactory>> refs; try { refs = new PriorityQueue<ServiceReference<IAgentServiceFactory>>(context.getServiceReferences(IAgentServiceFactory.class, "(" + IAgentServiceFactory.PROP_CREATED_SERVICE_NAME + '=' + serviceName + ')')); } catch (InvalidSyntaxException e) { e.printStackTrace(); return null; } if (refs == null || refs.isEmpty()) return null; ServiceReference<IAgentServiceFactory> firstRef = refs.iterator().next(); ServiceTracker<IAgentServiceFactory, Object> tracker = new ServiceTracker<IAgentServiceFactory, Object>(context, firstRef, this); tracker.open(); IAgentServiceFactory factory = (IAgentServiceFactory) tracker.getService(); if (factory == null) { tracker.close(); return null; } service = factory.createService(this); if (service == null) { tracker.close(); return null; } registerService(serviceName, service); trackers.put(firstRef, tracker); return service; } }

Target:
public Object getService(String serviceName) { synchronized (agentServices) { checkRunning(); Object service = agentServices.get(serviceName); if (service != null) return service; PriorityQueue<ServiceReference<IAgentServiceFactory>> refs; try { refs = new PriorityQueue<ServiceReference<IAgentServiceFactory>>(context.getServiceReferences(IAgentServiceFactory.class, "(" + IAgentServiceFactory.PROP_CREATED_SERVICE_NAME + '=' + serviceName + ')')); } catch (InvalidSyntaxException e) { e.printStackTrace(); return null; } if (refs == null || refs.isEmpty()) return null; ServiceReference<IAgentServiceFactory> firstRef = refs.peek(); ServiceTracker<IAgentServiceFactory, Object> tracker = new ServiceTracker<IAgentServiceFactory, Object>(context, firstRef, this); tracker.open(); IAgentServiceFactory factory = (IAgentServiceFactory) tracker.getService(); if (factory == null) { tracker.close(); return null; } service = factory.createService(this); if (service == null) { tracker.close(); return null; } registerService(serviceName, service); trackers.put(firstRef, tracker); return service; } }
Source:
public boolean navigate(Button.ClickEvent clickEvent) { BaseUI.getCurrentEventBus().getConsumerRegistry().unregister(new ResponseEntityKey()); BaseUI.getCurrent().getNavigator().navigateTo(navigateTo); return true; }

Target:
public boolean navigate(Button.ClickEvent clickEvent) { BaseUI.getCurrentEventBus().getConsumerRegistry().unregister(new ResponseEntityKey()); BaseUI.getCurrentNavigator().navigateTo(navigateTo); return true; }
Source:
public static void main(String[] args){ MenuWindow = new MenuFrame(); }

Target:
public static void main(String[] args){ menuwindow = new MenuFrame(); }
Source:
public long index(long... indices) { long index = 0; long[] physicalStrides = physicalStrides(sizes); for (int i = 0; i < indices.length && i < strides.length; i++) { long originalCoordinate = indices[i]; long mappedCoordinate = starts[i] + strides[i] * (originalCoordinate / blocks[i]) + (originalCoordinate % blocks[i]); index += mappedCoordinate * physicalStrides[i]; } return index; }

Target:
public long index(long... indices) { return index.index(indices); }
Source:
void performRetry(BitmapHunter hunter) { if (hunter.isCancelled()) return; if (service.isShutdown()) { performError(hunter, false); return; } NetworkInfo networkInfo = null; if (scansNetworkChanges) { ConnectivityManager connectivityManager = getService(context, CONNECTIVITY_SERVICE); networkInfo = connectivityManager.getActiveNetworkInfo(); } boolean hasConnectivity = networkInfo != null && networkInfo.isConnected(); boolean shouldRetryHunter = hunter.shouldRetry(airplaneMode, networkInfo); boolean supportsReplay = hunter.supportsReplay(); if (!shouldRetryHunter) { boolean willReplay = scansNetworkChanges && supportsReplay; performError(hunter, willReplay); if (willReplay) { markForReplay(hunter); } return; } if (!scansNetworkChanges || hasConnectivity) { hunter.future = service.submit(hunter); if (hunter.getPicasso().loggingEnabled) { log(OWNER_DISPATCHER, VERB_RETRIED, getLogIdsForHunter(hunter)); } return; } performError(hunter, supportsReplay); if (supportsReplay) { markForReplay(hunter); } }

Target:
void performRetry(BitmapHunter hunter) { if (hunter.isCancelled()) return; if (service.isShutdown()) { performError(hunter, false); return; } NetworkInfo networkInfo = null; if (scansNetworkChanges) { ConnectivityManager connectivityManager = getService(context, CONNECTIVITY_SERVICE); networkInfo = connectivityManager.getActiveNetworkInfo(); } boolean hasConnectivity = networkInfo != null && networkInfo.isConnected(); boolean shouldRetryHunter = hunter.shouldRetry(airplaneMode, networkInfo); boolean supportsReplay = hunter.supportsReplay(); if (!shouldRetryHunter) { boolean willReplay = scansNetworkChanges && supportsReplay; performError(hunter, willReplay); if (willReplay) { markForReplay(hunter); } return; } if (!scansNetworkChanges || hasConnectivity) { if (hunter.getPicasso().loggingEnabled) { log(OWNER_DISPATCHER, VERB_RETRYING, getLogIdsForHunter(hunter)); } hunter.future = service.submit(hunter); return; } performError(hunter, supportsReplay); if (supportsReplay) { markForReplay(hunter); } }
Source:
public Scope getScopeForInterface(final Integer nodeId, final String ipAddress) { if (nodeId == null || Strings.isNullOrEmpty(ipAddress)) { return EmptyScope.EMPTY; } final Scope metaDataScope = this.transactions.execute((tx) -> { final OnmsIpInterface ipInterface = this.ipInterfaceDao.findByNodeIdAndIpAddress(nodeId, ipAddress); if (ipInterface == null) { return EmptyScope.EMPTY; } return new FallbackScope(transform(ipInterface.getMetaData()), new ObjectScope<>(ipInterface) .map("interface", "hostname", (i) -> Optional.of(i.getIpHostName())) .map("interface", "address", (i) -> Optional.of(i.getIpAddress()).map(InetAddressUtils::toIpAddrString)) .map("interface", "netmask", (i) -> Optional.of(i.getNetMask()).map(InetAddressUtils::toIpAddrString)) .map("interface", "if-index", (i) -> Optional.ofNullable(i.getIfIndex()).map(Object::toString)) .map("interface", "if-alias", (i) -> Optional.of(i.getSnmpInterface().getIfAlias())) .map("interface", "if-description", (i) -> Optional.of(i.getSnmpInterface().getIfDescr())) .map("interface", "phy-addr", (i) -> Optional.of(i.getSnmpInterface().getPhysAddr())) ); }); return metaDataScope; }

Target:
public Scope getScopeForInterface(final Integer nodeId, final String ipAddress) { if (nodeId == null || Strings.isNullOrEmpty(ipAddress)) { return EmptyScope.EMPTY; } final Scope metaDataScope = this.transactions.execute((tx) -> { final OnmsIpInterface ipInterface = this.ipInterfaceDao.findByNodeIdAndIpAddress(nodeId, ipAddress); if (ipInterface == null) { return EmptyScope.EMPTY; } return new FallbackScope(transform(ipInterface.getMetaData()), new ObjectScope<>(ipInterface) .map("interface", "hostname", (i) -> Optional.ofNullable(i.getIpHostName())) .map("interface", "address", (i) -> Optional.ofNullable(i.getIpAddress()).map(InetAddressUtils::toIpAddrString)) .map("interface", "netmask", (i) -> Optional.ofNullable(i.getNetMask()).map(InetAddressUtils::toIpAddrString)) .map("interface", "if-index", (i) -> Optional.ofNullable(i.getIfIndex()).map(Object::toString)) .map("interface", "if-alias", (i) -> Optional.ofNullable(i.getSnmpInterface()).map(OnmsSnmpInterface::getIfAlias)) .map("interface", "if-description", (i) -> Optional.ofNullable(i.getSnmpInterface()).map(OnmsSnmpInterface::getIfDescr)) .map("interface", "phy-addr", (i) -> Optional.ofNullable(i.getSnmpInterface()).map(OnmsSnmpInterface::getPhysAddr)) ); }); return metaDataScope; }
Source:
public Command teslaScenario(TeslaScenario scenario, Integer target) { if (scenario == null) return seq(); scenario = (TeslaScenario) EcoreUtil.copy(scenario); selectorParser = new TeslaSelectorParser(scenario); selectorParser.parse(); teslaCommands = scenario.getCommands(); pos = 0; script = new ArrayList<Command>(); while (target == null || pos < target) { if (pos >= teslaCommands.size()) { break; } Command newCommand = teslaCommand(); if (newCommand != null) { script.add(newCommand); } } Sequence seq = CoreFactory.eINSTANCE.createSequence(); List<Command> withified = EclRefactoring.withify(script, new Comparator<Command>() { public int compare(Command c1, Command c2) { if (c1 instanceof Selector && c2 instanceof Selector) { Selector s1 = (Selector) c1; Selector s2 = (Selector) c2; if (s1.getId() != null && s2.getId() != null) { return s1.getId().compareTo(s2.getId()); } } if (c1 instanceof GetItemImpl && c2 instanceof GetItemImpl) { GetItemImpl i1 = (GetItemImpl) c1; GetItemImpl i2 = (GetItemImpl) c2; if (i1.getPath() != null && i2.getPath() != null) { return i1.getPath().compareTo(i2.getPath()); } } if (c1 instanceof GetMenuImpl && c2 instanceof GetMenuImpl) { GetMenuImpl m1 = (GetMenuImpl) c1; GetMenuImpl m2 = (GetMenuImpl) c2; if (m1.getPath() != null && m2.getPath() != null) { return m1.getPath().compareTo(m2.getPath()); } } return 1; } }); seq.getCommands().addAll(DiagramUtils.updateSelectors(withified)); return TeslaScriptletFactory.makeSeq(seq); }

Target:
public Command teslaScenario(TeslaScenario scenario, Integer target) { if (scenario == null) return seq(); scenario = (TeslaScenario) EcoreUtil.copy(scenario); selectorParser = new TeslaSelectorParser(scenario); selectorParser.parse(); teslaCommands = scenario.getCommands(); pos = 0; script = new ArrayList<Command>(); while (target == null || pos < target) { if (pos >= teslaCommands.size()) { break; } Command newCommand = teslaCommand(); if (newCommand != null) { script.add(newCommand); } } Sequence seq = CoreFactory.eINSTANCE.createSequence(); List<Command> withified = EclRefactoring.withify(script, new Comparator<Command>() { public int compare(Command c1, Command c2) { if (c1 instanceof Selector && c2 instanceof Selector) { Selector s1 = (Selector) c1; Selector s2 = (Selector) c2; if (s1.getId() != null && s2.getId() != null) { return s1.getId().compareTo(s2.getId()); } } if (c1 instanceof GetItem && c2 instanceof GetItem) { GetItem i1 = (GetItem) c1; GetItem i2 = (GetItem) c2; if (i1.getPath() != null && i2.getPath() != null) { return i1.getPath().compareTo(i2.getPath()); } } if (c1 instanceof GetMenu && c2 instanceof GetMenu) { GetMenu m1 = (GetMenu) c1; GetMenu m2 = (GetMenu) c2; if (m1.getPath() != null && m2.getPath() != null) { return m1.getPath().compareTo(m2.getPath()); } } return 1; } }); seq.getCommands().addAll(DiagramUtils.updateSelectors(withified)); return TeslaScriptletFactory.makeSeq(seq); }
Source:
public ContainerEngineeringTable(InventoryPlayer inventoryPlayer, TileEntityEngineeringTable tileEntityEngineeringTable) { tileEntity = tileEntityEngineeringTable; itemHandler = tileEntityEngineeringTable.getCapability(ITEM_HANDLER_CAPABILITY, null); assert itemHandler != null; addSlotToContainer(new SlotItemHandler(itemHandler, 0, 30, 35)); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 9; ++j) { addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } for (int i = 0; i < 4; ++i) { EntityEquipmentSlot equipmentSlot = ARMOR_SLOTS[i]; addSlotToContainer(new Slot(inventoryPlayer, inventoryPlayer.getSizeInventory() - 2 - i, 8, 8 + i * 18) { private EntityPlayer player = inventoryPlayer.player; @Override public int getSlotStackLimit() { return 1; } @Override public boolean isItemValid(ItemStack stack) { return !stack.isEmpty() && stack.getItem().isValidArmor(stack, equipmentSlot, player); } @Override @SideOnly(Side.CLIENT) public String getSlotTexture() { return ItemArmor.EMPTY_SLOT_NAMES[equipmentSlot.getIndex()]; } }); } addSlotToContainer(new Slot(inventoryPlayer, 40, 30, 62) { @Override @SideOnly(Side.CLIENT) public String getSlotTexture() { return "minecraft:items/empty_armor_slot_shield"; } }); for (int i = 0; i < 9; ++i) { addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); } prevNumSlots = inventorySlots.size(); numBaseSlots = prevNumSlots; updateUpgradeSlots(); }

Target:
public ContainerEngineeringTable(InventoryPlayer inventoryPlayer, TileEntityEngineeringTable tileEntityEngineeringTable) { tileEntity = tileEntityEngineeringTable; itemHandler = tileEntityEngineeringTable.getCapability(ITEM_HANDLER_CAPABILITY, null); addSlotToContainer(new SlotItemHandler(itemHandler, 0, 30, 35)); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 9; ++j) { addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } for (int i = 0; i < 4; ++i) { EntityEquipmentSlot equipmentSlot = ARMOR_SLOTS[i]; addSlotToContainer(new Slot(inventoryPlayer, inventoryPlayer.getSizeInventory() - 2 - i, 8, 8 + i * 18) { private EntityPlayer player = inventoryPlayer.player; @Override public int getSlotStackLimit() { return 1; } @Override public boolean isItemValid(ItemStack stack) { return !stack.isEmpty() && stack.getItem().isValidArmor(stack, equipmentSlot, player); } @Override @SideOnly(Side.CLIENT) public String getSlotTexture() { return ItemArmor.EMPTY_SLOT_NAMES[equipmentSlot.getIndex()]; } }); } addSlotToContainer(new Slot(inventoryPlayer, 40, 30, 62) { @Override @SideOnly(Side.CLIENT) public String getSlotTexture() { return "minecraft:items/empty_armor_slot_shield"; } }); for (int i = 0; i < 9; ++i) { addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); } prevNumSlots = inventorySlots.size(); numBaseSlots = prevNumSlots; updateUpgradeSlots(); }
Source:
private static boolean isEnclosingClassFinal(ExpressionTree expressionTree) { if (expressionTree.is(IDENTIFIER)) { Tree parent = expressionTree.parent(); while (!parent.is(METHOD, CONSTRUCTOR, INITIALIZER)) { parent = parent.parent(); } if (parent instanceof MethodTree) { return ((MethodTree) parent).symbol().owner().isFinal(); } else { return ((ClassTree) parent.parent()).symbol().isFinal(); } } return ((MemberSelectExpressionTree) expressionTree).expression().symbolType().symbol().isFinal(); }

Target:
private static boolean isEnclosingClassFinal(ExpressionTree expressionTree) { if (expressionTree.is(IDENTIFIER)) { MethodTree methodTree = findMethodTreeAncestor(expressionTree); if (methodTree != null) { return methodTree.symbol().owner().isFinal(); } else { return findClassTreeAncestor(expressionTree).symbol().isFinal(); } } return ((MemberSelectExpressionTree) expressionTree).expression().symbolType().symbol().isFinal(); }
Source:
public static void waitUntilViewWithGivenTitleShows(final String viewTitle) { waitForView(new BaseMatcher<IViewReference>() { public boolean matches(Object item) { if (item instanceof IViewReference) { return viewTitle.equals(((IViewReference) item).getTitle()); } return false; } public void describeTo(Description description) { description.appendText("Wait for view with title " + viewTitle); } }); }

Target:
public static void waitUntilViewWithGivenTitleShows(final String viewTitle) { waitForView(new BaseMatcher<IViewReference>() { public boolean matches(Object item) { if (item instanceof IViewReference) return viewTitle.equals(((IViewReference) item).getTitle()); return false; } public void describeTo(Description description) { description.appendText("Wait for view with title " + viewTitle); } }); }
Source:
protected String escapeDoubleQuotes(final String str) { return str.replace("\"", "\\\""); }

Target:
private String escapeDoubleQuotes(final String str) { return str.replace("\"", "\\\""); }
Source:
private boolean isHttpsOnly(final DeploymentPhaseContext phaseContext, final DeploymentUnit unit) { CapabilityServiceSupport serviceSupport = unit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); ServiceName undertowServiceName = serviceSupport.getCapabilityServiceName("org.wildfly.undertow"); ServiceController<?> undertowServiceController = phaseContext.getServiceRegistry().getService(undertowServiceName); UndertowService undertowService = (UndertowService) undertowServiceController.getValue(); Server defaultServer = null; for (Server server : undertowService.getServers()) { if (server.getName().equals("default-server")) { defaultServer = server; } } if (defaultServer == null) return false; List<String> listeners = new ArrayList<>(); for (UndertowListener listener : defaultServer.getListeners()) { listeners.add(listener.getProtocol()); } if (listeners.size() == 1) { return "https".equals(listeners.get(0)); } return false; }

Target:
private boolean isHttpsOnly(final DeploymentPhaseContext phaseContext, final DeploymentUnit unit) { CapabilityServiceSupport serviceSupport = unit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); ServiceName undertowServiceName = serviceSupport.getCapabilityServiceName("org.wildfly.undertow"); ServiceController<?> undertowServiceController = phaseContext.getServiceRegistry().getService(undertowServiceName); UndertowService undertowService = (UndertowService) undertowServiceController.getValue(); for (Server server : undertowService.getServers()) { if (server.getName().equals(undertowService.getDefaultServer())) { if ("https".equals(server.getListeners().get(0).getProtocol())) return true; } } return false; }
Source:
protected ChannelManager() { channelMap = new HashMap<String, Channel>(); }

Target:
private ChannelManager() { channelMap = new HashMap<String, Channel>(); }
Source:
private static void waitForStreamState(AmazonKinesisClient kinesisClient, String streamName, @Nullable StreamStatus expectedStatus) { long waitTime = System.currentTimeMillis() + TIMEOUT; while (System.currentTimeMillis() < waitTime) { try { TimeUnit.MILLISECONDS.sleep(SLEEP_INTERVAL); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } StreamStatus streamState = streamExists(kinesisClient, streamName) ? getStreamState(kinesisClient, streamName) : null; if (expectedStatus == streamState) { return; } } throw new IllegalStateException(String.format("TimedOut waithing for stream to be in %s state", expectedStatus)); }

Target:
private static void waitForStreamState(AmazonKinesisClient kinesisClient, String streamName, @Nullable StreamStatus expectedStatus) { long waitTime = System.currentTimeMillis() + TIMEOUT; while (System.currentTimeMillis() < waitTime) { try { TimeUnit.MILLISECONDS.sleep(SLEEP_INTERVAL); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } StreamStatus streamState = streamExists(kinesisClient, streamName) ? getStreamState(kinesisClient, streamName) : null; if (expectedStatus == streamState) { return; } } throw new IllegalStateException(String.format("Timed out waiting for stream to be in %s state", expectedStatus)); }
Source:
protected void updateCompactionMark(CorfuRuntime runtime, long compactionMark) { if (runtime.getAddressSpaceView().getCompactionMark() < compactionMark) { runtime.getAddressSpaceView().setCompactionMark(compactionMark); log.trace("Compaction mark is updated to {}", compactionMark); } }

Target:
protected void updateCompactionMark(CorfuRuntime runtime, long compactionMark) { runtime.getAddressSpaceView().getCompactionMark().getAndUpdate((address) -> { if (address < compactionMark) { log.trace("Compaction mark is updated to {}", compactionMark); return compactionMark; } else { return address; } }); }
Source:
public List<Command> transmit(final List<Command> commands) { LOG.trace("transmitting commands", commands.size()); if (serverConnector == null) { LOG.debug("no server connector wired for in-memory connector"); return Collections.EMPTY_LIST; } if (sleepMillis > 0) { try { Thread.sleep(sleepMillis); } catch (InterruptedException e) { throw new RuntimeException(e); } } List<Command> result = new LinkedList<Command>(); for (Command command : commands) { LOG.trace("processing {}", command); result.addAll(serverConnector.receive(command)); } return result; }

Target:
public List<Command> transmit(final List<Command> commands) { LOG.trace("transmitting commands", commands.size()); if (serverConnector == null) { LOG.warn("no server connector wired for in-memory connector"); return Collections.EMPTY_LIST; } if (sleepMillis > 0) { try { Thread.sleep(sleepMillis); } catch (InterruptedException e) { throw new RuntimeException(e); } } List<Command> result = new LinkedList<Command>(); for (Command command : commands) { LOG.trace("processing {}", command); result.addAll(serverConnector.receive(command)); } return result; }
Source:
public List<String> getJournalKeysFromDois(List<String> dois, Site site) throws IOException { if (dois.isEmpty()) { return new ArrayList<String>(); } List<String> quoted = dois.stream().map(doi -> { return "\"" + QueryParser.escape(doi) + "\""; }).collect(Collectors.toList()); ArticleSearchQuery explicitDoiSearchQuery = ArticleSearchQuery.builder() .setSimple(false) .setRows(dois.size()) .setQuery("id:(" + String.join(" OR ", quoted) + ")") .setIsJournalSearch(true) .build(); Map<String, ?> results = solrSearchApi.search(explicitDoiSearchQuery, site); List<Map<String, ?>> docs = (List<Map<String, ?>>) results.get("docs"); Map<String, String> keysMap = new HashMap<String,String>(); docs.stream().forEach(data -> { keysMap.put((String) data.get("id"), (String) data.get("journal_key")); }); List<String> journalKeys = dois.stream().map(id -> { if (keysMap.containsKey(id)) { return keysMap.get(id); } else { return ""; } }).collect(Collectors.toList()); return journalKeys; }

Target:
public List<String> getJournalKeysFromDois(List<String> dois, Site site) throws IOException { if (dois.isEmpty()) { return new ArrayList<String>(); } List<String> quoted = dois.stream().map(doi -> { return "\"" + QueryParser.escape(doi) + "\""; }).collect(Collectors.toList()); ArticleSearchQuery explicitDoiSearchQuery = ArticleSearchQuery.builder() .setSimple(false) .setRows(dois.size()) .setQuery("id:(" + String.join(" OR ", quoted) + ")") .setIsJournalSearch(true) .build(); Map<String, ?> results = solrSearchApi.search(explicitDoiSearchQuery, site); List<Map<String, ?>> docs = (List<Map<String, ?>>) results.get("docs"); Map<String, String> keysMap = new HashMap<String,String>(); docs.forEach(data -> { keysMap.put((String) data.get("id"), (String) data.get("journal_key")); }); List<String> journalKeys = dois.stream().map(id -> { if (keysMap.containsKey(id)) { return keysMap.get(id); } else { return ""; } }).collect(Collectors.toList()); return journalKeys; }
Source:
protected Response exportPersistenceData(MementoCopyMode preferredOrigin) { if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ALL_SERVER_INFO, null)) throw WebResourceUtils.unauthorized("User '%s' is not authorized for this operation", Entitlements.getEntitlementContext().user()); try { String label = mgmt().getManagementNodeId()+"-"+Time.makeDateSimpleStampString(); PersistenceObjectStore targetStore = BrooklynPersistenceUtils.newPersistenceObjectStore(mgmt(), null, "web-persistence-"+label+"-"+Identifiers.makeRandomId(4)); BrooklynPersistenceUtils.writeMemento(mgmt(), targetStore, preferredOrigin); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ArchiveBuilder.zip().addDirContentsAt( ((FileBasedObjectStore)targetStore).getBaseDir(), "/" ).stream(baos); String filename = "brooklyn-state-"+label+".zip"; return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM_TYPE) .header("Content-Disposition","attachment; filename = "+filename) .build(); } catch (Exception e) { log.warn("Unable to serve persistence data (rethrowing): "+e, e); throw Exceptions.propagate(e); } }

Target:
protected Response exportPersistenceData(MementoCopyMode preferredOrigin) { if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ALL_SERVER_INFO, null)) throw WebResourceUtils.unauthorized("User '%s' is not authorized for this operation", Entitlements.getEntitlementContext().user()); try { String label = mgmt().getManagementNodeId()+"-"+Time.makeDateSimpleStampString(); PersistenceObjectStore targetStore = BrooklynPersistenceUtils.newPersistenceObjectStore(mgmt(), null, "web-persistence-"+label+"-"+Identifiers.makeRandomId(4)); BrooklynPersistenceUtils.writeMemento(mgmt(), targetStore, preferredOrigin); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ArchiveBuilder.zip().addDirContentsAt( ((FileBasedObjectStore)targetStore).getBaseDir(), ((FileBasedObjectStore)targetStore).getBaseDir().getName() ).stream(baos); String filename = "brooklyn-state-"+label+".zip"; return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM_TYPE) .header("Content-Disposition","attachment; filename = "+filename) .build(); } catch (Exception e) { log.warn("Unable to serve persistence data (rethrowing): "+e, e); throw Exceptions.propagate(e); } }
Source:
private boolean checkLunsInStorageDomain(List<String> lunIds, StorageDomain storageDomain) { List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); List<String> lunsList = new ArrayList<>(lunIds); for (LUNs lun : lunsFromDb) { if (lunsList.contains(lun.getLUN_id())) { lunsList.remove(lun.getLUN_id()); } } return lunsList.isEmpty(); }

Target:
private boolean checkLunsInStorageDomain(List<String> lunIds, StorageDomain storageDomain) { List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); Set<String> lunsList = new HashSet<>(lunIds); for (LUNs lun : lunsFromDb) { if (lunsList.contains(lun.getLUN_id())) { lunsList.remove(lun.getLUN_id()); } } return lunsList.isEmpty(); }