auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean bootstrapSchedules(Iterable<Channel> channels, Interval interval, Publisher source) { if (bootstrapLock.tryLock()) { bootstrapping.set(true); processed.set(0); failures.set(0); Set<ListenableFuture<UpdateProgress>> futures = Sets.newHashSet(); log.info( "Bootstrapping channels for interval from to {}", Iterables.size(channels), interval.getStart(), interval.getEnd() ); try { for (Channel channel : channels) { log.info("Bootstrapping channel {}/{}", channel.getId(), channel.getTitle()); ListenableFuture<UpdateProgress> updateFuture = executor.submit( taskFactory.create(source, channel, interval) ); Futures.addCallback(updateFuture, new FutureCallback<UpdateProgress>() { @Override public void onSuccess(UpdateProgress result) { processed.incrementAndGet(); log.info("Processed channel with updates {}", result); } @Override public void onFailure(Throwable t) { log.error("Error while processing schedules", t); failures.incrementAndGet(); lastException.set(t); } }); futures.add(updateFuture); } Futures.get(Futures.allAsList(futures), Exception.class); } catch (Exception e) { lastException.set(e); } finally { bootstrapLock.unlock(); bootstrapping.set(false); } return true; } else { return false; } }

Target:
public boolean bootstrapSchedules(Iterable<Channel> channels, Interval interval, Publisher source) { if (!bootstrapLock.tryLock()) { return false; } bootstrapping.set(true); processed.set(0); failures.set(0); Set<ListenableFuture<UpdateProgress>> futures = Sets.newHashSet(); log.info( "Bootstrapping channels for interval from to {}", Iterables.size(channels), interval.getStart(), interval.getEnd() ); try { for (Channel channel : channels) { futures.add(bootstrapChannel(channel, interval, source)); } Futures.get(Futures.allAsList(futures), Exception.class); } catch (Exception e) { } finally { bootstrapLock.unlock(); bootstrapping.set(false); } return true; }
Source:
public void handleError(HttpCommand command, HttpResponse response) { String message = parseMessage(response); Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); try { message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: if ((command.getCurrentRequest().getEndpoint().getPath().endsWith("/info")) || (message != null && message.indexOf("could not be found") != -1)) exception = new ResourceNotFoundException(message, exception); else if (message != null && message.indexOf("currently in use") != -1) exception = new IllegalStateException(message, exception); else exception = new IllegalArgumentException(message, exception); break; case 401: exception = new AuthorizationException(message, exception); break; case 402: exception = new IllegalStateException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 405: exception = new IllegalArgumentException(message, exception); break; case 409: exception = new IllegalStateException(message, exception); break; } } finally { closeQuietly(response.getPayload()); command.setException(exception); } }

Target:
public void handleError(HttpCommand command, HttpResponse response) { Exception exception = null; try { String message = parseMessage(response); message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: exception = new AuthorizationException(message, exception); break; case 404: if (command.getCurrentRequest().getMethod().equals("GET")) { if (command.getCurrentRequest().getEndpoint().getPath().endsWith("/images/json")) { exception = new HttpResponseException("Unable to reach docker daemon", command, response); } } break; case 409: if (command.getCurrentRequest().getMethod().equals("POST")) { if (command.getCurrentRequest().getEndpoint().getPath().endsWith("/containers")) { exception = new HttpResponseException("Container already exists", command, response); } } break; case 500: if (command.getCurrentRequest().getMethod().equals("POST")) { if (command.getCurrentRequest().getEndpoint().getPath().endsWith("/engines")) { exception = new HttpResponseException("Connection refused registering docker daemon", command, response); } } break; default: exception = new HttpResponseException(message, command, response); break; } } catch (Exception e) { exception = new HttpResponseException(command, response, e); } finally { closeQuietly(response.getPayload()); command.setException(exception); } }
Source:
public void testClearMetaEntryInfo() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method clearMetaEntryInfo = DeviceTypeManagementServiceImpl.class.getDeclaredMethod("clearMetaEntryInfo", DeviceType.class); clearMetaEntryInfo.setAccessible(true); DeviceType deviceType = new DeviceType(); deviceType.setId(TEST_DEVICE_TYPE_ID); deviceType.setName(TEST_DEVICE_TYPE); DeviceTypeMetaDefinition deviceTypeMetaDefinition = new DeviceTypeMetaDefinition(); deviceTypeMetaDefinition.setClaimable(true); deviceTypeMetaDefinition.setDescription(DEVICE_TYPE_DESCRIPTION); PushNotificationConfig pushNotificationConfig = new PushNotificationConfig(TEST_DEVICE_TYPE, true, null); deviceTypeMetaDefinition.setPushNotificationConfig(pushNotificationConfig); deviceType.setDeviceTypeMetaDefinition(deviceTypeMetaDefinition); DeviceType returned = (DeviceType) clearMetaEntryInfo.invoke(this.deviceTypeManagementService, deviceType); Assert.assertNotNull(returned.getDeviceTypeMetaDefinition()); }

Target:
public void testClearMetaEntryInfo() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method clearMetaEntryInfo = DeviceTypeManagementServiceImpl.class.getDeclaredMethod("clearMetaEntryInfo", DeviceType.class); clearMetaEntryInfo.setAccessible(true); DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID); DeviceType returned = (DeviceType) clearMetaEntryInfo.invoke(this.deviceTypeManagementService, deviceType); Assert.assertNotNull(returned.getDeviceTypeMetaDefinition(), "The response object is null."); }
Source:
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isInterface()) { return data; } Map<MethodNameDeclaration, List<NameOccurrence>> methods = node.getScope().getEnclosingScope(ClassScope.class) .getMethodDeclarations(); for (MethodNameDeclaration mnd : findUnique(methods)) { List<NameOccurrence> occs = methods.get(mnd); if (!privateAndNotExcluded(mnd) || ((Annotateable) mnd.getNode()).isAnyAnnotationPresent(getProperty(ignoredAnnotationsDescriptor))) { continue; } if (occs.isEmpty()) { addViolation(data, mnd.getNode(), mnd.getImage() + mnd.getParameterDisplaySignature()); } else { if (calledFromOutsideItself(occs, mnd)) { addViolation(data, mnd.getNode(), mnd.getImage() + mnd.getParameterDisplaySignature()); } } } return data; }

Target:
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isInterface()) { return data; } Map<MethodNameDeclaration, List<NameOccurrence>> methods = node.getScope().getEnclosingScope(ClassScope.class) .getMethodDeclarations(); for (MethodNameDeclaration mnd : findUnique(methods)) { List<NameOccurrence> occs = methods.get(mnd); if (!privateAndNotExcluded(mnd) || hasIgnoredAnnotation((Annotatable) mnd.getNode().jjtGetParent())) { continue; } if (occs.isEmpty()) { addViolation(data, mnd.getNode(), mnd.getImage() + mnd.getParameterDisplaySignature()); } else { if (calledFromOutsideItself(occs, mnd)) { addViolation(data, mnd.getNode(), mnd.getImage() + mnd.getParameterDisplaySignature()); } } } return data; }
Source:
public void testServerTemplateProps() { setServerProp(KieServerConfigurationKey.LOCATION, SERVER_LOCATION); setServerProp(KieServerConfigurationKey.USER, SERVER_USER); setServerProp(KieServerConfigurationKey.PASSWORD, SERVER_PASSWORD); KieServerConnectionInfo connectionInfo = kieServerConnectionInfoProvider.verifiedConnectionInfo(def); assertEquals(SERVER_LOCATION, connectionInfo.getLocation().get()); assertEquals(SERVER_USER, connectionInfo.getUser().get()); assertEquals(SERVER_PASSWORD, connectionInfo.getPassword().get()); }

Target:
public void testServerTemplateProps() { setServerProp(KieServerConfigurationKey.LOCATION, SERVER_LOCATION); setServerProp(KieServerConfigurationKey.USER, SERVER_USER); setServerProp(KieServerConfigurationKey.PASSWORD, SERVER_PASSWORD); KieServerConnectionInfo connectionInfo = kieServerConnectionInfoProvider.verifiedConnectionInfo(def); assertEquals(SERVER_LOCATION, connectionInfo.getLocation().get()); assertEquals(SERVER_USER, connectionInfo.getUser().get()); assertEquals(SERVER_PASSWORD, connectionInfo.getPassword().get()); assertFalse(connectionInfo.isReplaceQuery()); }
Source:
static void setDefaults() { setDefault(FEATURE_POLICY_PERSISTENCE_PROPERTY, true); setDefault(FEATURE_ENRICHER_PERSISTENCE_PROPERTY, true); setDefault(FEATURE_FEED_PERSISTENCE_PROPERTY, true); setDefault(FEATURE_FEED_REGISTRATION_PROPERTY, false); setDefault(FEATURE_CATALOG_PERSISTENCE_PROPERTY, true); setDefault(FEATURE_DEFAULT_STANDBY_IS_HOT_PROPERTY, false); setDefault(FEATURE_USE_BROOKLYN_LIVE_OBJECTS_DATAGRID_STORAGE, false); setDefault(FEATURE_RENAME_THREADS, false); setDefault(FEATURE_INFER_CATALOG_ITEM_ON_REBIND, true); setDefault(FEATURE_SSH_ASYNC_EXEC, true); }

Target:
static void setDefaults() { setDefault(FEATURE_POLICY_PERSISTENCE_PROPERTY, true); setDefault(FEATURE_ENRICHER_PERSISTENCE_PROPERTY, true); setDefault(FEATURE_FEED_PERSISTENCE_PROPERTY, true); setDefault(FEATURE_FEED_REGISTRATION_PROPERTY, false); setDefault(FEATURE_CATALOG_PERSISTENCE_PROPERTY, true); setDefault(FEATURE_DEFAULT_STANDBY_IS_HOT_PROPERTY, false); setDefault(FEATURE_USE_BROOKLYN_LIVE_OBJECTS_DATAGRID_STORAGE, false); setDefault(FEATURE_RENAME_THREADS, false); setDefault(FEATURE_INFER_CATALOG_ITEM_ON_REBIND, true); setDefault(FEATURE_SSH_ASYNC_EXEC, false); }
Source:
public synchronized void registerCapability(RuntimeCapabilityRegistration capabilityRegistration) { CapabilityId capabilityId = capabilityRegistration.getCapabilityId(); RegistrationPoint rp = capabilityRegistration.getOldestRegistrationPoint(); RuntimeCapabilityRegistration currentRegistration = capabilities.get(capabilityId); if (currentRegistration != null) { if (!safeEquals(capabilityRegistration.getCapability(), currentRegistration.getCapability()) || !currentRegistration.addRegistrationPoint(rp)) { throw ControllerLogger.MGMT_OP_LOGGER.capabilityAlreadyRegisteredInContext(capabilityId.getName(), capabilityId.getContext().getName()); } } else { capabilities.put(capabilityId, capabilityRegistration); } for (String req : capabilityRegistration.getCapability().getRequirements()) { registerRequirement(new RuntimeRequirementRegistration(req, capabilityId.getName(), capabilityId.getContext(), rp)); } if (!forServer) { CapabilityContext capContext = capabilityId.getContext(); if (!satisfiedByMap.containsKey(capContext)) { Set<CapabilityContext> satisfiesUs = new HashSet<>(); satisfiedByMap.put(capContext, satisfiesUs); for (Map.Entry<CapabilityContext, Set<CapabilityContext>> entry : satisfiedByMap.entrySet()) { if (entry.getKey().canSatisfyRequirements(capContext)) { satisfiesUs.add(entry.getKey()); } if (capContext.canSatisfyRequirements(entry.getKey())) { entry.getValue().add(capContext); } } } } }

Target:
public synchronized void registerCapability(RuntimeCapabilityRegistration capabilityRegistration) { CapabilityId capabilityId = capabilityRegistration.getCapabilityId(); RegistrationPoint rp = capabilityRegistration.getOldestRegistrationPoint(); RuntimeCapabilityRegistration currentRegistration = capabilities.get(capabilityId); if (currentRegistration != null) { if (!Objects.equals(capabilityRegistration.getCapability(), currentRegistration.getCapability()) || !currentRegistration.addRegistrationPoint(rp)) { throw ControllerLogger.MGMT_OP_LOGGER.capabilityAlreadyRegisteredInContext(capabilityId.getName(), capabilityId.getContext().getName()); } } else { capabilities.put(capabilityId, capabilityRegistration); } for (String req : capabilityRegistration.getCapability().getRequirements()) { registerRequirement(new RuntimeRequirementRegistration(req, capabilityId.getName(), capabilityId.getContext(), rp)); } if (!forServer) { CapabilityContext capContext = capabilityId.getContext(); if (!satisfiedByMap.containsKey(capContext)) { Set<CapabilityContext> satisfiesUs = new HashSet<>(); satisfiedByMap.put(capContext, satisfiesUs); for (Map.Entry<CapabilityContext, Set<CapabilityContext>> entry : satisfiedByMap.entrySet()) { if (entry.getKey().canSatisfyRequirements(capContext)) { satisfiesUs.add(entry.getKey()); } if (capContext.canSatisfyRequirements(entry.getKey())) { entry.getValue().add(capContext); } } } } }
Source:
public String generateSelectSql (String namespace, Requirement minimumRequirement) { String fieldsString; String tableName = String.join(".", namespace, name); if (minimumRequirement.equals(EDITOR)) fieldsString = fieldsToString(editorFields(), tableName + "."); else if (minimumRequirement.equals(OPTIONAL)) fieldsString = fieldsToString(specFields(), tableName + "."); else if (minimumRequirement.equals(REQUIRED)) fieldsString = fieldsToString(requiredFields(), tableName + "."); else fieldsString = "*"; return String.format("select %s from %s", fieldsString, tableName); }

Target:
public String generateSelectSql (String namespace, Requirement minimumRequirement) { String fieldsString; String tableName = String.join(".", namespace, name); String fieldPrefix = tableName + "."; if (minimumRequirement.equals(EDITOR)) fieldsString = commaSeparatedNames(editorFields(), fieldPrefix); else if (minimumRequirement.equals(OPTIONAL)) fieldsString = commaSeparatedNames(specFields(), fieldPrefix); else if (minimumRequirement.equals(REQUIRED)) fieldsString = commaSeparatedNames(requiredFields(), fieldPrefix); else fieldsString = "*"; return String.format("select %s from %s", fieldsString, tableName); }
Source:
public void stop() { if (isStarted()) { log.debugf("Stopping remote cache manager %x", (Integer) System.identityHashCode(this)); synchronized (cacheName2RemoteCache) { for (Map.Entry<RemoteCacheKey, RemoteCacheHolder> cache : cacheName2RemoteCache.entrySet()) { cache.getValue().remoteCache().stop(); } cacheName2RemoteCache.clear(); } listenerNotifier.stop(); counterManager.stop(); channelFactory.destroy(); } unregisterMBean(); started = false; }

Target:
public void stop() { if (isStarted()) { log.debugf("Stopping remote cache manager %x", System.identityHashCode(this)); synchronized (cacheName2RemoteCache) { for (Map.Entry<RemoteCacheKey, RemoteCacheHolder> cache : cacheName2RemoteCache.entrySet()) { cache.getValue().remoteCache().stop(); } cacheName2RemoteCache.clear(); } listenerNotifier.stop(); counterManager.stop(); channelFactory.destroy(); } unregisterMBean(); started = false; }
Source:
public static String getFactoryId() { return "org.eclipse.cdt.dsf.debug.simpleMapPersistableFactory"; }

Target:
public static String getFactoryId() { return "org.eclipse.cdt.dsf.ui.simpleMapPersistableFactory"; }
Source:
public void testIOConsoleAvailable() throws Exception { IOConsole console = new IOConsole("", null); try (InputStream consoleInput = console.getInputStream()) { consoleInput.available(); consoleInput.available(); } console = new IOConsole("", null); try (InputStream consoleInput = console.getInputStream()) { consoleInput.available(); new Thread(() -> { try { Thread.sleep(100); consoleInput.close(); } catch (Exception e) { } }).start(); assertEquals("read() did not signaled EOF.", -1, consoleInput.read()); } console = new IOConsole("", null); try (InputStream consoleInput = console.getInputStream()) { consoleInput.close(); consoleInput.available(); consoleInput.available(); } }

Target:
public void testIOConsoleAvailable() throws Exception { IOConsole console = new IOConsole("", null); try (InputStream consoleInput = console.getInputStream()) { consoleInput.available(); consoleInput.available(); } console = new IOConsole("", null); try (InputStream consoleInput = console.getInputStream()) { consoleInput.available(); new Thread(() -> { try { Thread.sleep(100); consoleInput.close(); } catch (Exception e) { } }).start(); assertEquals("read() did not signal EOF.", -1, consoleInput.read()); } console = new IOConsole("", null); try (InputStream consoleInput = console.getInputStream()) { consoleInput.close(); consoleInput.available(); consoleInput.available(); } }
Source:
public void setContents(IFileState source, int updateFlags, IProgressMonitor monitor) throws CoreException { }

Target:
public void setContents(IFileState source, int updateFlags, IProgressMonitor monitor) throws CoreException { delegate().setContents(source, updateFlags, monitor); }
Source:
public ECKey getKey() { final ECKey key = ECKey.fromPrivate(Arrays.copyOf(bytes, 32)); return isCompressed() ? key : key.decompress(); }

Target:
public ECKey getKey() { return ECKey.fromPrivate(Arrays.copyOf(bytes, 32), isCompressed()); }
Source:
public ParseSpec withDimensionsSpec(DimensionsSpec spec) { return new JSONParseSpec(getTimestampSpec(), spec, flattenSpec); }

Target:
public ParseSpec withDimensionsSpec(DimensionsSpec spec) { return new JSONParseSpec(getTimestampSpec(), spec, getFlattenSpec()); }
Source:
private TypePrinter<GraphQLEnumType> enumPrinter() { return (out, type, visibility) -> { if (isIntrospectionType(type)) { return; } GraphqlTypeComparatorEnvironment environment = GraphqlTypeComparatorEnvironment.newEnvironment() .parentType(GraphQLEnumType.class) .elementType(GraphQLEnumValueDefinition.class) .build(); Comparator<? super GraphQLType> comparator = options.comparatorRegistry.getComparator(environment); printComments(out, type, ""); out.format("enum %s%s {\n", type.getName(), directivesString(GraphQLEnumType.class, type.getDirectives())); List<GraphQLEnumValueDefinition> values = type.getValues() .stream() .sorted(comparator) .collect(toList()); for (GraphQLEnumValueDefinition enumValueDefinition : values) { printComments(out, enumValueDefinition, " "); List<GraphQLDirective> enumValueDirectives = enumValueDefinition.getDirectives(); if (enumValueDefinition.isDeprecated()) { enumValueDirectives = addDeprecatedDirectiveIfNeeded(enumValueDirectives); } out.format(" %s%s\n", enumValueDefinition.getName(), directivesString(GraphQLEnumValueDefinition.class, enumValueDirectives)); } out.format("}\n\n"); }; }

Target:
private TypePrinter<GraphQLEnumType> enumPrinter() { return (out, type, visibility) -> { if (isIntrospectionType(type)) { return; } GraphqlTypeComparatorEnvironment environment = GraphqlTypeComparatorEnvironment.newEnvironment() .parentType(GraphQLEnumType.class) .elementType(GraphQLEnumValueDefinition.class) .build(); Comparator<? super GraphQLSchemaElement> comparator = options.comparatorRegistry.getComparator(environment); if (shouldPrintAsAst(type.getDefinition())) { printAsAst(out, type.getDefinition(), type.getExtensionDefinitions()); } else { printComments(out, type, ""); out.format("enum %s%s {\n", type.getName(), directivesString(GraphQLEnumType.class, type.getDirectives())); List<GraphQLEnumValueDefinition> values = type.getValues() .stream() .sorted(comparator) .collect(toList()); for (GraphQLEnumValueDefinition enumValueDefinition : values) { printComments(out, enumValueDefinition, " "); List<GraphQLDirective> enumValueDirectives = enumValueDefinition.getDirectives(); if (enumValueDefinition.isDeprecated()) { enumValueDirectives = addDeprecatedDirectiveIfNeeded(enumValueDirectives); } out.format(" %s%s\n", enumValueDefinition.getName(), directivesString(GraphQLEnumValueDefinition.class, enumValueDirectives)); } out.format("}\n\n"); } }; }
Source:
public OuiaComponentTypeAttribute ouiaComponentType() { return new OuiaComponentTypeAttribute("tree-item"); }

Target:
public OuiaComponentTypeAttribute ouiaComponentType() { return new OuiaComponentTypeAttribute(OUIA_COMPONENT_TYPE); }
Source:
protected void commitWithRetries(Consumer<?, ?> consumer, Optional<Map<TopicPartition, OffsetAndMetadata>> offsets) throws DatastreamRuntimeException { preCommitHook(); AtomicReference<KafkaException> lastKafkaExceptionRef = new AtomicReference<>(null); boolean result = PollUtils.poll(() -> { try { if (offsets.isPresent()) { consumer.commitSync(offsets.get(), _commitTimeout); _kafkaTopicPartitionTracker.onOffsetsCommitted(offsets.get()); } else { consumer.commitSync(_commitTimeout); } _logger.info("Commit succeeded."); } catch (KafkaException e) { lastKafkaExceptionRef.set(e); if (_shutdown) { _logger.info("Caught KafkaException in commitWithRetries while shutting down, so exiting.", e); return true; } _logger.warn(String.format("Commit failed with exception. DatastreamTask = %s", _datastreamTask.getDatastreamTaskName()), e); return false; } return true; }, COMMIT_RETRY_INTERVAL_MILLIS, COMMIT_RETRY_TIMEOUT_MILLIS); postCommitHook(result, lastKafkaExceptionRef.get()); if (!result) { String msg = "Commit failed after several retries, Giving up."; _logger.error(msg); throw new DatastreamRuntimeException(msg); } }

Target:
protected void commitWithRetries(Consumer<?, ?> consumer, Optional<Map<TopicPartition, OffsetAndMetadata>> offsets) throws DatastreamRuntimeException { preCommitHook(); boolean result = PollUtils.poll(() -> { try { if (offsets.isPresent()) { consumer.commitSync(offsets.get(), _commitTimeout); _kafkaTopicPartitionTracker.onOffsetsCommitted(offsets.get()); } else { consumer.commitSync(_commitTimeout); } _logger.info("Commit succeeded."); } catch (KafkaException e) { if (_shutdown) { _logger.info("Caught KafkaException in commitWithRetries while shutting down, so exiting.", e); return true; } _logger.warn(String.format("Commit failed with exception. DatastreamTask = %s", _datastreamTask.getDatastreamTaskName()), e); return false; } return true; }, COMMIT_RETRY_INTERVAL_MILLIS, COMMIT_RETRY_TIMEOUT_MILLIS); if (!result) { String msg = "Commit failed after several retries, Giving up."; _logger.error(msg); throw new DatastreamRuntimeException(msg); } }
Source:
private void disposeSuccessfulTest(BaseRealm testRealm) { looperThread.postRunnable(() -> { if (subscription != null) { subscription.dispose(); } if (!testRealm.getConfiguration().equals(realm.getConfiguration())) { throw new IllegalStateException("This method only works for Realms with the same configuration as the looper Realm"); } testRealm.close(); if (!realm.equals(testRealm)) { realm.close(); } looperThread.postRunnable(new Runnable() { @Override public void run() { RealmLog.error("Global: " + Realm.getGlobalInstanceCount(testRealm.getConfiguration())); RealmLog.error("Local: " + Realm.getGlobalInstanceCount(testRealm.getConfiguration())); if (Realm.getGlobalInstanceCount(testRealm.getConfiguration()) == 0) { looperThread.testComplete(); } else { RealmLog.error("" + Realm.getGlobalInstanceCount(testRealm.getConfiguration())); looperThread.postRunnable(this); } } }); }); }

Target:
private void disposeSuccessfulTest(BaseRealm testRealm) { looperThread.postRunnable(() -> { if (subscription != null) { subscription.dispose(); } if (!testRealm.getConfiguration().equals(realm.getConfiguration())) { throw new IllegalStateException("This method only works for Realms with the same configuration as the looper Realm"); } testRealm.close(); if (!realm.equals(testRealm)) { realm.close(); } looperThread.postRunnable(new Runnable() { @Override public void run() { if (Realm.getGlobalInstanceCount(testRealm.getConfiguration()) == 0) { looperThread.testComplete(); } else { RealmLog.error("" + Realm.getGlobalInstanceCount(testRealm.getConfiguration())); looperThread.postRunnable(this); } } }); }); }
Source:
public int hashCode() { int result = cl != null ? cl.hashCode() : 0; result = 31 * result + (transport != null ? transport.hashCode() : 0); result = 31 * result + (globalJmxStatistics != null ? globalJmxStatistics.hashCode() : 0); result = 31 * result + (serialization != null ? serialization.hashCode() : 0); result = 31 * result + (evictionThreadPool != null ? evictionThreadPool.hashCode() : 0); result = 31 * result + (listenerThreadPool != null ? listenerThreadPool.hashCode() : 0); result = 31 * result + (replicationQueueThreadPool != null ? replicationQueueThreadPool.hashCode() : 0); result = 31 * result + (persistenceThreadPool != null ? persistenceThreadPool.hashCode() : 0); result = 31 * result + (shutdown != null ? shutdown.hashCode() : 0); result = 31 * result + (site != null ? site.hashCode() : 0); return result; }

Target:
public int hashCode() { int result = cl != null ? cl.hashCode() : 0; result = 31 * result + (transport.hashCode()); result = 31 * result + (globalJmxStatistics.hashCode()); result = 31 * result + (serialization.hashCode()); result = 31 * result + (evictionThreadPool.hashCode()); result = 31 * result + (listenerThreadPool.hashCode()); result = 31 * result + (replicationQueueThreadPool.hashCode()); result = 31 * result + (persistenceThreadPool.hashCode()); result = 31 * result + (shutdown.hashCode()); result = 31 * result + (site.hashCode()); result = 31 * result + (security.hashCode()); return result; }
Source:
public void setMarkerCluster(GMarkerCluster markerCluster) { this.markerCluster = markerCluster; add(new GMapMarkerClustererHeaderContributor()); }

Target:
public void setMarkerCluster(GMarkerCluster markerCluster) { if(markerCluster == null) throw new IllegalArgumentException("GMarkerCluster argument should not be null."); this.markerCluster = markerCluster; if (getBehaviors(GMapMarkerClustererHeaderContributor.class).isEmpty()) { add(new GMapMarkerClustererHeaderContributor()); } }
Source:
public String toString() { return "(" + label + ", " + status + ", " + appliedBy + ")"; }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(label).append(": ").append(status); if (appliedBy != null) { sb.append(" by ").append(appliedBy); } return sb.toString(); }
Source:
public RepositoryDirectoryValue.Builder fetch(Rule rule, Path outputDirectory, BlazeDirectories directories, Environment env, Map<String, String> markerData) throws RepositoryFunctionException, InterruptedException { SkylarkSemantics skylarkSemantics = PrecomputedValue.SKYLARK_SEMANTICS.get(env); if (skylarkSemantics == null) { return null; } if (skylarkSemantics.incompatibleRemoveNativeMavenJar()) { throw new RepositoryFunctionException( new EvalException( null, "The native maven_jar rule is deprecated." + " add details about replacement here." + "\nUse --incompatible_remove_native_maven_jar=false to temporarily continue" + " using the native rule."), Transience.PERSISTENT); } MavenServerValue serverValue = getServer(rule, env); if (env.valuesMissing()) { return null; } Path outputDir = getExternalRepositoryDirectory(directories).getRelative(rule.getName()); return createOutputTree(rule, outputDir, serverValue, env.getListener()); }

Target:
public RepositoryDirectoryValue.Builder fetch(Rule rule, Path outputDirectory, BlazeDirectories directories, Environment env, Map<String, String> markerData) throws RepositoryFunctionException, InterruptedException { SkylarkSemantics skylarkSemantics = PrecomputedValue.SKYLARK_SEMANTICS.get(env); if (skylarkSemantics == null) { return null; } if (skylarkSemantics.incompatibleRemoveNativeMavenJar()) { throw new RepositoryFunctionException( new EvalException( null, "The native maven_jar rule is deprecated." + " See <LINK_0>" + "backward-compatibility.html#remove-native-maven-jar for migration information." + "\nUse --incompatible_remove_native_maven_jar=false to temporarily continue" + " using the native rule."), Transience.PERSISTENT); } MavenServerValue serverValue = getServer(rule, env); if (env.valuesMissing()) { return null; } Path outputDir = getExternalRepositoryDirectory(directories).getRelative(rule.getName()); return createOutputTree(rule, outputDir, serverValue, env.getListener()); }
Source:
private PackList scanPacksImpl(final PackList old) { final Map<String, PackFile> forReuse = reuseMap(old); final FileSnapshot snapshot = FileSnapshot.save(packDirectory); final Set<String> names = listPackDirectory(); final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2); boolean foundNew = false; for (final String indexName : names) { if (indexName.length() != 49 || !indexName.endsWith(".idx")) continue; final String base = indexName.substring(0, indexName.length() - 3); final List<PackExt> extensions = new ArrayList<PackExt>( PackExt.values().length); for (PackExt ext : PackExt.values()) { if (names.contains(base + ext.getExtension())) extensions.add(ext); } if (!extensions.contains(PACK)) { continue; } final String packName = base + PACK.getExtension(); final PackFile oldPack = forReuse.remove(packName); if (oldPack != null) { list.add(oldPack); continue; } final File packFile = new File(packDirectory, packName); list.add(new PackFile(packFile, extensions)); foundNew = true; } if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) { old.snapshot.setClean(snapshot); return old; } for (final PackFile p : forReuse.values()) { p.close(); } if (list.isEmpty()) return new PackList(snapshot, NO_PACKS.packs); final PackFile[] r = list.toArray(new PackFile[list.size()]); Arrays.sort(r, PackFile.SORT); return new PackList(snapshot, r); }

Target:
private PackList scanPacksImpl(final PackList old) { final Map<String, PackFile> forReuse = reuseMap(old); final FileSnapshot snapshot = FileSnapshot.save(packDirectory); final Set<String> names = listPackDirectory(); final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2); boolean foundNew = false; for (final String indexName : names) { if (indexName.length() != 49 || !indexName.endsWith(".idx")) continue; final String base = indexName.substring(0, indexName.length() - 3); int extensions = 0; for (PackExt ext : PackExt.values()) { if (names.contains(base + ext.getExtension())) extensions |= 1 << ext.getPosition(); } if ((extensions & 1 << PACK.getPosition()) == 0) { continue; } final String packName = base + PACK.getExtension(); final PackFile oldPack = forReuse.remove(packName); if (oldPack != null) { list.add(oldPack); continue; } final File packFile = new File(packDirectory, packName); list.add(new PackFile(packFile, extensions)); foundNew = true; } if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) { old.snapshot.setClean(snapshot); return old; } for (final PackFile p : forReuse.values()) { p.close(); } if (list.isEmpty()) return new PackList(snapshot, NO_PACKS.packs); final PackFile[] r = list.toArray(new PackFile[list.size()]); Arrays.sort(r, PackFile.SORT); return new PackList(snapshot, r); }
Source:
protected static Iterator<Object[]> invokeDataProvider(Object instance, Method dataProvider, ITestNGMethod method, ITestContext testContext, Object fedInstance, IAnnotationFinder annotationFinder) { List<Object> parameters = getParameters(dataProvider, method, testContext, fedInstance, annotationFinder); Object result = invokeMethodNoCheckedException(dataProvider, instance, parameters); if (result instanceof Object[][]) { return new ArrayIterator((Object[][]) result); } else if (result instanceof Object[]) { return new OneToTwoDimArrayIterator((Object[]) result); } else if (result instanceof Iterator) { Type returnType = dataProvider.getGenericReturnType(); if (returnType instanceof ParameterizedType) { ParameterizedType contentType = (ParameterizedType) returnType; Class<?> type = (Class<?>) contentType.getActualTypeArguments()[0]; if (type.isArray()) { return (Iterator<Object[]>) result; } else { return new OneToTwoDimIterator((Iterator<Object>) result); } } else { return (Iterator<Object[]>) result; } } throw new TestNGException("Data Provider " + dataProvider + " must return" + " either Object[][] or Object[] or Iterator<Object>[], not " + dataProvider.getReturnType()); }

Target:
protected static Iterator<Object[]> invokeDataProvider(Object instance, Method dataProvider, ITestNGMethod method, ITestContext testContext, Object fedInstance, IAnnotationFinder annotationFinder) { List<Object> parameters = getParameters(dataProvider, method, testContext, fedInstance, annotationFinder); Object result = invokeMethodNoCheckedException(dataProvider, instance, parameters); if (result instanceof Object[][]) { return new ArrayIterator((Object[][]) result); } else if (result instanceof Object[]) { return new OneToTwoDimArrayIterator((Object[]) result); } else if (result instanceof Iterator) { Type returnType = dataProvider.getGenericReturnType(); if (returnType instanceof ParameterizedType) { ParameterizedType contentType = (ParameterizedType) returnType; Class<?> type = (Class<?>) contentType.getActualTypeArguments()[0]; if (type.isArray()) { return (Iterator<Object[]>) result; } else { return new OneToTwoDimIterator((Iterator<Object>) result); } } else { return (Iterator<Object[]>) result; } } throw new TestNGException("Data Provider " + dataProvider + " must return" + " either Object[][] or Object[] or Iterator<Object[]> or Iterator<Object>, not " + dataProvider.getReturnType()); }
Source:
public void testKeepComment() throws Exception { IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test;\r\n"); buf.append("import java.util.Collection;\r\n"); buf.append("import java.util.Iterator;\r\n"); buf.append("public class A {\r\n"); buf.append(" Collection<String> c;\r\n"); buf.append(" public A() {\r\n"); buf.append(" for (final Iterator<String> iterator= c.iterator(); iterator.hasNext();) {\r\n"); buf.append(" buf.append(" String test= iterator.next();\r\n"); buf.append(" System.out.println(test);\r\n"); buf.append(" }\r\n");buf.append(" }\r\n"); buf.append("}"); ICompilationUnit unit= pack.createCompilationUnit("A.java", buf.toString(), false, null); List<IJavaCompletionProposal> proposals= fetchConvertingProposal(buf, unit); assertNotNull(fConvertLoopProposal); assertCorrectLabels(proposals); String preview= getPreviewContent(fConvertLoopProposal); buf= new StringBuffer(); buf.append("package test;\r\n"); buf.append("import java.util.Collection;\r\n"); buf.append("public class A {\r\n"); buf.append(" Collection<String> c;\r\n"); buf.append(" public A() {\r\n"); buf.append(" for (String test : c) {\r\n"); buf.append(" buf.append(" System.out.println(test);\r\n"); buf.append(" }\r\n"); buf.append(" }\r\n"); buf.append("}"); String expected= buf.toString(); assertEqualString(preview, expected); }

Target:
public void testKeepComment() throws Exception { IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test;\n"); buf.append("import java.util.Collection;\n"); buf.append("import java.util.Iterator;\n"); buf.append("public class A {\n"); buf.append(" Collection<String> c;\n"); buf.append(" public A() {\n"); buf.append(" for (final Iterator<String> iterator= c.iterator(); iterator.hasNext();) {\n"); buf.append(" buf.append(" String test= iterator.next();\n"); buf.append(" System.out.println(test);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}"); ICompilationUnit unit= pack.createCompilationUnit("A.java", buf.toString(), false, null); List<IJavaCompletionProposal> proposals= fetchConvertingProposal(buf, unit); assertNotNull(fConvertLoopProposal); assertCorrectLabels(proposals); String preview= getPreviewContent(fConvertLoopProposal); buf= new StringBuffer(); buf.append("package test;\n"); buf.append("import java.util.Collection;\n"); buf.append("public class A {\n"); buf.append(" Collection<String> c;\n"); buf.append(" public A() {\n"); buf.append(" for (String test : c) {\n"); buf.append(" buf.append(" System.out.println(test);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}"); String expected= buf.toString(); assertEqualString(preview, expected); }
Source:
public void testAccessViewFsPathWithoutAuthority() throws Exception { final Path hdfsTargetPath = new Path(defaultFSURI + HDFS_USER_FOLDER); addMountLinks(defaultFSURI.getAuthority(), new String[] {HDFS_USER_FOLDER, LOCAL_FOLDER }, new String[] {hdfsTargetPath.toUri().toString(), localTargetDir.toURI().toString() }, conf); Path hdfsDir = new Path(HDFS_USER_FOLDER + "/test"); Path localDir = new Path(LOCAL_FOLDER + "/test"); try (ViewFileSystemOverloadScheme fs = (ViewFileSystemOverloadScheme) FileSystem.get(conf)) { fs.mkdirs(hdfsDir); fs.mkdirs(localDir); } FileStatus[] expectedStatus; try (FileSystem fs = FileSystem.get(conf)) { expectedStatus = fs.listStatus(new Path("/")); } Path viewFsRootPath = new Path("viewfs:/"); try { viewFsRootPath.getFileSystem(conf); Assert.fail("Mount table with authority default should not be initialized"); } catch (IOException e) { assertTrue(e.getMessage().contains("Empty Mount table in config for viewfs://default/")); } conf.set(Constants.CONFIG_VIEWFS_DEFAULT_MOUNT_TABLE_NAME_KEY, defaultFSURI.getAuthority()); try (FileSystem fs = viewFsRootPath.getFileSystem(conf)) { FileStatus[] status = fs.listStatus(viewFsRootPath); List<String> expectedPaths = Arrays.stream(expectedStatus).map(s -> s.getPath().getName()).collect(Collectors.toList()); List<String> paths = Arrays.stream(status).map(s -> s.getPath().getName()).collect(Collectors.toList()); assertEquals(expectedPaths, paths); } }

Target:
public void testAccessViewFsPathWithoutAuthority() throws Exception { final Path hdfsTargetPath = new Path(defaultFSURI + HDFS_USER_FOLDER); addMountLinks(defaultFSURI.getAuthority(), new String[] {HDFS_USER_FOLDER, LOCAL_FOLDER }, new String[] {hdfsTargetPath.toUri().toString(), localTargetDir.toURI().toString() }, conf); Path hdfsDir = new Path(HDFS_USER_FOLDER, "test"); Path localDir = new Path(LOCAL_FOLDER, "test"); FileStatus[] expectedStatus; try (FileSystem fs = FileSystem.get(conf)) { fs.mkdirs(hdfsDir); fs.mkdirs(localDir); expectedStatus = fs.listStatus(new Path("/")); } Path viewFsRootPath = new Path("viewfs:/"); try { viewFsRootPath.getFileSystem(conf); Assert.fail( "Mount table with authority default should not be initialized"); } catch (IOException e) { assertTrue(e.getMessage().contains( "Empty Mount table in config for viewfs://default/")); } conf.set(Constants.CONFIG_VIEWFS_DEFAULT_MOUNT_TABLE_NAME_KEY, defaultFSURI.getAuthority()); try (FileSystem fs = viewFsRootPath.getFileSystem(conf)) { FileStatus[] status = fs.listStatus(viewFsRootPath); List<String> expectedPaths = Arrays.stream(expectedStatus) .map(s -> s.getPath().getName()).sorted() .collect(Collectors.toList()); List<String> paths = Arrays.stream(status) .map(s -> s.getPath().getName()).sorted() .collect(Collectors.toList()); assertEquals(expectedPaths, paths); } }
Source:
static int getUnstaged(@Nullable IndexDiffData indexDiff) { if (indexDiff == null) { return 0; } int size = indexDiff.getUntracked().size(); size += indexDiff.getMissing().size(); size += indexDiff.getModified().size(); size += indexDiff.getConflicting().size(); return size; }

Target:
private static int getUnstaged(@Nullable IndexDiffData indexDiff) { if (indexDiff == null) { return 0; } int size = indexDiff.getUntracked().size(); size += indexDiff.getMissing().size(); size += indexDiff.getModified().size(); size += indexDiff.getConflicting().size(); return size; }
Source:
public void testUnmarshallSubprocessLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateMessageEventCatching emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_OUTGOING_EDGE_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertMessageEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, ""); assertDataIOSet(emptySubprocessEvent.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallSubprocessLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateMessageEventCatching emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_OUTGOING_EDGE_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertMessageEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, EMPTY_VALUE); assertDataIOSet(emptySubprocessEvent.getDataIOSet(), EMPTY_VALUE); }
Source:
public List<CommitValidationMessage> onCommitReceived( CommitReceivedEvent receiveEvent) throws CommitValidationException { final List<String> idList = receiveEvent.commit.getFooterLines(CHANGE_ID); List<CommitValidationMessage> messages = new LinkedList<CommitValidationMessage>(); if (idList.isEmpty()) { if (projectControl.getProjectState().isRequireChangeID()) { String shortMsg = receiveEvent.commit.getShortMessage(); String changeIdPrefix = CHANGE_ID.getName() + ":"; if (shortMsg.startsWith(changeIdPrefix) && shortMsg.substring(changeIdPrefix.length()).trim() .matches("^I[0-9a-f]{8,}.*$")) { throw new CommitValidationException( "missing subject, Change-Id must be in commit message footer"); } else { String errMsg = "missing Change-Id in commit message footer"; messages.add(getFixedCommitMsgWithChangeId( errMsg, receiveEvent.commit)); throw new CommitValidationException(errMsg, messages); } } } else if (idList.size() > 1) { throw new CommitValidationException( "multiple Change-Id lines in commit message footer", messages); } else { final String v = idList.get(idList.size() - 1).trim(); if (!v.matches("^I[0-9a-f]{8,}.*$")) { final String errMsg = "missing or invalid Change-Id line format in commit message footer"; messages.add( getFixedCommitMsgWithChangeId(errMsg, receiveEvent.commit)); throw new CommitValidationException(errMsg, messages); } } return Collections.emptyList(); }

Target:
public List<CommitValidationMessage> onCommitReceived( CommitReceivedEvent receiveEvent) throws CommitValidationException { final List<String> idList = receiveEvent.commit.getFooterLines(CHANGE_ID); List<CommitValidationMessage> messages = new LinkedList<CommitValidationMessage>(); if (idList.isEmpty()) { if (projectControl.getProjectState().isRequireChangeID()) { String shortMsg = receiveEvent.commit.getShortMessage(); String changeIdPrefix = CHANGE_ID.getName() + ":"; if (shortMsg.startsWith(changeIdPrefix) && shortMsg.substring(changeIdPrefix.length()).trim() .matches("^I[0-9a-f]{8,}.*$")) { throw new CommitValidationException( "missing subject; Change-Id must be in commit message footer"); } else { String errMsg = "missing Change-Id in commit message footer"; messages.add(getFixedCommitMsgWithChangeId( errMsg, receiveEvent.commit)); throw new CommitValidationException(errMsg, messages); } } } else if (idList.size() > 1) { throw new CommitValidationException( "multiple Change-Id lines in commit message footer", messages); } else { final String v = idList.get(idList.size() - 1).trim(); if (!v.matches("^I[0-9a-f]{8,}.*$")) { final String errMsg = "missing or invalid Change-Id line format in commit message footer"; messages.add( getFixedCommitMsgWithChangeId(errMsg, receiveEvent.commit)); throw new CommitValidationException(errMsg, messages); } } return Collections.emptyList(); }
Source:
public User populate(ModelTranslator modelTranslator, UserDTO source, User destination) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (destination == null) { throw new IllegalArgumentException("destination is null"); } destination.setCreated(source.getCreated() != null ? new Date(source.getCreated().toInstant().toEpochMilli()) : null); destination.setUpdated(source.getUpdated() != null ? new Date(source.getUpdated().toInstant().toEpochMilli()) : null); destination.setId(source.getId()); destination.setUsername(source.getUsername()); destination.setSuperAdmin(source.getSuperAdmin()); destination.setPassword(source.getPassword() != null ? Util.hash(source.getPassword()) : null); destination.setHashedPassword(source.getPassword() != null ? Util.hash(source.getPassword()) : null); return destination; }

Target:
public User populate(ModelTranslator modelTranslator, UserDTO source, User destination) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (destination == null) { throw new IllegalArgumentException("destination is null"); } destination.setCreated(source.getCreated() != null ? new Date(source.getCreated().toInstant().toEpochMilli()) : null); destination.setUpdated(source.getUpdated() != null ? new Date(source.getUpdated().toInstant().toEpochMilli()) : null); destination.setUsername(source.getUsername()); destination.setSuperAdmin(source.getSuperAdmin() == null ? false : source.getSuperAdmin()); destination.setHashedPassword(source.getPassword() != null ? Util.hash(source.getPassword()) : null); return destination; }
Source:
public static RemoteConfig findRemoteConfig(Config config, String remoteName) throws URISyntaxException { List<RemoteConfig> allRemoteConfigs; RemoteConfig remoteConfig = null; allRemoteConfigs = RemoteConfig.getAllRemoteConfigs(config); for (RemoteConfig rc : allRemoteConfigs) { if (rc.getName().equals(remoteName)) remoteConfig = rc; } return remoteConfig; }

Target:
public static RemoteConfig findRemoteConfig(Config config, String remoteName) throws URISyntaxException { RemoteConfig remoteConfig = null; List<RemoteConfig> allRemoteConfigs = RemoteConfig .getAllRemoteConfigs(config); for (RemoteConfig rc : allRemoteConfigs) { if (rc.getName().equals(remoteName)) { remoteConfig = rc; break; } } return remoteConfig; }
Source:
public Allergies setAllergies(Patient patient, Allergies allergies) { List<Allergy> dbAllergyList = getAllergies(patient); for (Allergy originalAllergy : dbAllergyList) { if (allergies.contains(originalAllergy)) { Allergy potentiallyEditedAllergy = allergies.getAllergy(originalAllergy.getAllergyId()); if (!potentiallyEditedAllergy.hasSameValues(originalAllergy)) { Allergy newAllergy = new Allergy(); try { allergies.remove(potentiallyEditedAllergy); newAllergy.copy(potentiallyEditedAllergy); allergies.add(newAllergy); voidAllergy(originalAllergy); } catch (Exception ex) { throw new APIException("Failed to copy edited values", ex); } } continue; } voidAllergy(originalAllergy); } for (Allergy allergy : allergies) { if (allergy.getAllergyId() == null && allergy.getAllergen().getCodedAllergen() == null && StringUtils.isNotBlank(allergy.getAllergen().getNonCodedAllergen())) { String otherNonCodedConceptUuid = Context.getAdministrationService().getGlobalProperty(OpenmrsConstants.GP_ALLERGEN_OTHER_NON_CODED_UUID); Concept otherNonCoded = Context.getConceptService().getConceptByUuid(otherNonCodedConceptUuid); if (otherNonCoded == null) { throw new APIException("Can't find concept with uuid:" + otherNonCodedConceptUuid); } allergy.getAllergen().setCodedAllergen(otherNonCoded); } } return dao.saveAllergies(patient, allergies); }

Target:
public Allergies setAllergies(Patient patient, Allergies allergies) { List<Allergy> dbAllergyList = getAllergies(patient); for (Allergy originalAllergy : dbAllergyList) { if (allergies.contains(originalAllergy)) { Allergy potentiallyEditedAllergy = allergies.getAllergy(originalAllergy.getAllergyId()); if (!potentiallyEditedAllergy.hasSameValues(originalAllergy)) { Allergy newAllergy = new Allergy(); try { allergies.remove(potentiallyEditedAllergy); newAllergy.copy(potentiallyEditedAllergy); allergies.add(newAllergy); voidAllergy(originalAllergy); } catch (Exception ex) { throw new APIException("Failed to copy edited values", ex); } } continue; } voidAllergy(originalAllergy); } for (Allergy allergy : allergies) { if (allergy.getAllergyId() == null && allergy.getAllergen().getCodedAllergen() == null && StringUtils.isNotBlank(allergy.getAllergen().getNonCodedAllergen())) { Concept otherNonCoded = Context.getConceptService().getConceptByUuid(Allergen.getOtherNonCodedConceptUuid()); if (otherNonCoded == null) { throw new APIException("Can't find concept with uuid:" + Allergen.getOtherNonCodedConceptUuid()); } allergy.getAllergen().setCodedAllergen(otherNonCoded); } } return dao.saveAllergies(patient, allergies); }