auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void runTest() throws Throwable { assertNotNull("TestCase.name cannot be null", name); Method runMethod = null; try { runMethod = getClass().getMethod(name, (Class[]) null); } catch (NoSuchMethodException e) { fail("Method \"" + name + "\" not found"); } if (!Modifier.isPublic(runMethod.getModifiers())) { fail("Method \"" + name + "\" should be public"); } try { runMethod.invoke(this); } catch (InvocationTargetException e) { e.fillInStackTrace(); throw e.getTargetException(); } catch (IllegalAccessException e) { e.fillInStackTrace(); throw e; } }

Target:
protected void runTest() throws Throwable { assertNotNull("TestCase name cannot be null", name); Method runMethod = null; try { runMethod = getClass().getMethod(name, (Class[]) null); } catch (NoSuchMethodException e) { fail("Method \"" + name + "\" not found"); } if (!Modifier.isPublic(runMethod.getModifiers())) { fail("Method \"" + name + "\" should be public"); } try { runMethod.invoke(this); } catch (InvocationTargetException e) { e.fillInStackTrace(); throw e.getTargetException(); } catch (IllegalAccessException e) { e.fillInStackTrace(); throw e; } }
Source:
private void setStructureDependencies(final PublisherFilter publisherFilter) throws DotDataException, DotSecurityException { try { for (String inode : contentTypesSet) { structureDependencyHelper(inode,publisherFilter); } } catch (DotDataException e) { Logger.error(this, e.getMessage(),e); } }

Target:
private void setStructureDependencies(final PublisherFilter publisherFilter) throws DotDataException, DotSecurityException { try { for (final String inode : contentTypesSet) { structureDependencyHelper(inode,publisherFilter); } } catch (DotDataException e) { Logger.error(this, e.getMessage(),e); } }
Source:
public void verify_fallback_in_download_presigned_urls() throws Exception { AmazonServiceException firstException = new AmazonServiceException("Didn't find Object Id in bucket"); firstException.setStatusCode(HttpStatus.NOT_FOUND.value()); int bucketPoolSize = 32; int bucketKeySize = 2; ReflectionTestUtils.setField(service, "bucketPoolSize", bucketPoolSize); ReflectionTestUtils.setField(service, "bucketKeySize", bucketKeySize); ObjectURLGenerator urlGen = new AmazonURLGenerator(); ReflectionTestUtils.setField(urlGen, "s3Client", ObjectDownloadServiceStubFactory.createS3ClientForRadosGW(endpointUrl)); ReflectionTestUtils.setField(service, "urlGenerator", urlGen); when(s3Client.getObject(Mockito.any())).thenThrow(firstException); List<Part> parts = ObjectDownloadServiceStubFactory.createParts(5); ObjectSpecification os = ObjectDownloadServiceStubFactory.createObjectSpecification(objectId, ObjectKeys.getObjectKey(dataDir, objectId), 104857600); os.setParts(parts); os.setRelocated(true); ObjectDownloadService sut = spy(service); doReturn(os).when(sut).getSpecification(objectId); val objSpec = sut.download(objectId, 0, 104857600, false); Part p = objSpec.getParts().get(0); URL url = new URL(p.getUrl()); String path = url.getPath(); if (path.startsWith("/")) { path = path.substring(1, path.length() - 1); } String bucket = Splitter.on('/').trimResults().omitEmptyStrings().split(path).iterator().next(); assertEquals(dataBucketName, bucket); System.out.println(); }

Target:
public void verify_fallback_in_download_presigned_urls() throws Exception { val firstException = new AmazonServiceException("Didn't find Object Id in bucket"); firstException.setStatusCode(HttpStatus.NOT_FOUND.value()); int bucketPoolSize = 32; int bucketKeySize = 2; namingService.setBucketPoolSize(bucketPoolSize); namingService.setBucketKeySize(bucketKeySize); val urlGen = new AmazonURLGenerator(); ReflectionTestUtils.setField(urlGen, "s3Client", ObjectDownloadServiceStubFactory.createS3ClientForRadosGW(endpointUrl)); ReflectionTestUtils.setField(service, "urlGenerator", urlGen); when(s3Client.getObject(Mockito.any())).thenThrow(firstException); val parts = ObjectDownloadServiceStubFactory.createParts(5); val os = ObjectDownloadServiceStubFactory.createObjectSpecification(objectId, ObjectKeys.getObjectKey(dataDir, objectId), 104857600); os.setParts(parts); os.setRelocated(true); val sut = spy(service); doReturn(os).when(sut).getSpecification(objectId); val objSpec = sut.download(objectId, 0, 104857600, false); val p = objSpec.getParts().get(0); val url = new URL(p.getUrl()); String path = url.getPath(); if (path.startsWith("/")) { path = path.substring(1, path.length() - 1); } val bucket = Splitter.on('/').trimResults().omitEmptyStrings().split(path).iterator().next(); assertEquals(objectBucketName, bucket); System.out.println(); }
Source:
public void activate() { hueBridgeHandler.registerLightStatusListener(this); logger.info("Hue Light Discovery Service activated."); }

Target:
public void activate() { hueBridgeHandler.registerLightStatusListener(this); }
Source:
public ReadPreference getReadPreference() { if (readPreferenceTagSets.isEmpty()) { return readPreference.getReadPreference(); } else { return ReadPreference.valueOf(readPreference.name(), getReadPreferenceTags()); } }

Target:
public ReadPreferenceType getReadPreference() { return readPreference; }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; }

Target:
public int hashCode() { return Objects.hashCode(name); }
Source:
private void checkComment(GHIssueComment comment) throws IOException { GHUser sender = comment.getUser(); String body = comment.getBody(); if (helper.isRequestForTestingPhrase(body)) { logger.log(Level.FINEST, "'Request for testing' comment from bot user {0} ignored.", sender); return; } if (helper.isWhitelistPhrase(body) && helper.isAdmin(sender)) { if (!helper.isWhitelisted(author)) { logger.log(Level.FINEST, "Author {0} not whitelisted, adding to whitelist.", author); helper.addWhitelist(author.getLogin()); } accepted = true; shouldRun = true; } else if (helper.isOktotestPhrase(body) && helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} gave OK to test", sender); accepted = true; shouldRun = true; } else if (helper.isRetestPhrase(body)) { logger.log(Level.FINEST, "Retest phrase"); if (helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} gave retest phrase", sender); shouldRun = true; } else if (accepted && helper.isWhitelisted(sender)) { logger.log(Level.FINEST, "Retest accepted and user {0} is whitelisted", sender); shouldRun = true; triggered = true; } } else if (helper.isTriggerPhrase(body)) { logger.log(Level.FINEST, "Trigger phrase"); if (helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} ran trigger phrase", sender); shouldRun = true; triggered = true; } else if (accepted && helper.isWhitelisted(sender)) { logger.log(Level.FINEST, "Trigger accepted and user {0} is whitelisted", sender); shouldRun = true; triggered = true; } } }

Target:
private void checkComment(GHIssueComment comment) throws IOException { GHUser sender = comment.getUser(); String body = comment.getBody(); if (helper.isBotUser(sender)) { logger.log(Level.FINEST, "Comment from bot user {0} ignored.", sender); return; } if (helper.isWhitelistPhrase(body) && helper.isAdmin(sender)) { if (!helper.isWhitelisted(author)) { logger.log(Level.FINEST, "Author {0} not whitelisted, adding to whitelist.", author); helper.addWhitelist(author.getLogin()); } accepted = true; shouldRun = true; } else if (helper.isOktotestPhrase(body) && helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} gave OK to test", sender); accepted = true; shouldRun = true; } else if (helper.isRetestPhrase(body)) { logger.log(Level.FINEST, "Retest phrase"); if (helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} gave retest phrase", sender); shouldRun = true; } else if (accepted && helper.isWhitelisted(sender)) { logger.log(Level.FINEST, "Retest accepted and user {0} is whitelisted", sender); shouldRun = true; triggered = true; } } else if (helper.isTriggerPhrase(body)) { logger.log(Level.FINEST, "Trigger phrase"); if (helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} ran trigger phrase", sender); shouldRun = true; triggered = true; } else if (accepted && helper.isWhitelisted(sender)) { logger.log(Level.FINEST, "Trigger accepted and user {0} is whitelisted", sender); shouldRun = true; triggered = true; } } if (shouldRun) { triggerSender = sender; commentBody = body; } }
Source:
public void testAllNodesFollowOneLeader() { ICluster seed = Cluster.joinAwait(); LeaderElection seedLeader = createLeaderElection(seed); List<LeaderElection> leaders = createCluster(seed); awaitSeconds(30); Address seedLeaderAddress = seedLeader.leader(); for (LeaderElection m : leaders) { Address memberLeaderAddress = m.leader(); assertTrue("Expected leader address " + seedLeaderAddress + ", but actual: " + memberLeaderAddress, memberLeaderAddress.equals(seedLeaderAddress)); } for (LeaderElection m : leaders) { m.cluster().shutdown(); } seed.shutdown(); }

Target:
public void testAllNodesFollowOneLeader() { ICluster seed = Cluster.joinAwait(); LeaderElection seedLeader = createLeaderElection(seed); Queue<LeaderElection> leaders = createCluster(seed, NUM_OF_NODES); awaitSeconds(4); Member seedMember = leaders.peek().leader(); for (LeaderElection m : leaders) { Member member = m.leader(); assertTrue("Expected leader address " + seedMember.address() + ", but actual: " + member.address(), member.equals(seedMember)); } teardownCluster(seed, leaders); }
Source:
private Provider<KubevirtProviderProperties> getProvider() { return backend.runInternalQuery(QueryType.GetProviderById, new IdQueryParameters(getCachedVm().getClusterId())).getReturnValue(); }

Target:
private Provider<KubevirtProviderProperties> getProvider() { return (Provider<KubevirtProviderProperties>) providerDao.get(getCachedVm().getClusterId()); }
Source:
public void testDifferentGAVsWithAlias() throws Exception { Long oldPid = processClient.startProcess(CONTAINER_ALIAS, PROCESS_ID_EVALUATION); assertNotNull(oldPid); assertTrue(oldPid > 0); ProcessInstance processInstance = processClient.getProcessInstance(CONTAINER_ALIAS, oldPid); assertNotNull(processInstance); assertEquals(CONTAINER_ID, processInstance.getContainerId()); ReleaseId differentReleaseId101 = new ReleaseId("org.kie.server.different", "different-gav-definition-project", "1.0.1.Final"); KieContainerResource containerResource = new KieContainerResource(CONTAINER_ID_101, differentReleaseId101); containerResource.setContainerAlias(CONTAINER_ALIAS); client.createContainer(CONTAINER_ID_101, containerResource); Long pid = processClient.startProcess(CONTAINER_ALIAS, PROCESS_ID_EVALUATION_2); assertNotNull(pid); assertTrue(pid > 0); processInstance = processClient.getProcessInstance(CONTAINER_ALIAS, pid); assertNotNull(processInstance); assertEquals(CONTAINER_ID_101, processInstance.getContainerId()); }

Target:
public void testDifferentGAVsWithAlias() throws Exception { Long oldPid = processClient.startProcess(CONTAINER_ALIAS, PROCESS_ID_EVALUATION); assertThat(oldPid).isNotNull().isGreaterThan(0); ProcessInstance processInstance = processClient.getProcessInstance(CONTAINER_ALIAS, oldPid); assertThat(processInstance).isNotNull(); assertThat(processInstance.getContainerId()).isEqualTo(CONTAINER_ID); ReleaseId differentReleaseId101 = new ReleaseId("org.kie.server.different", "different-gav-definition-project", "1.0.1.Final"); KieContainerResource containerResource = new KieContainerResource(CONTAINER_ID_101, differentReleaseId101); containerResource.setContainerAlias(CONTAINER_ALIAS); client.createContainer(CONTAINER_ID_101, containerResource); Long pid = processClient.startProcess(CONTAINER_ALIAS, PROCESS_ID_EVALUATION_2); assertThat(pid).isNotNull().isGreaterThan(0); processInstance = processClient.getProcessInstance(CONTAINER_ALIAS, pid); assertThat(processInstance).isNotNull(); assertThat(processInstance.getContainerId()).isEqualTo(CONTAINER_ID_101); }
Source:
private void validateScope(Set<String> scopes) throws OAuthProblemException{ for(String s: scopes) { String[] scopeParts = s.split(":"); Application application = applicationService.find(scopeParts[0]); if(application == null || (scopeParts.length > 1 && !application.hasScope(scopeParts[1]))) throw OAuthProblemException.error("invalid_request", String.format("Invalid scope %s", s)); } }

Target:
private void validateScope(Set<String> scopes) throws OAuthProblemException{ for(String s: scopes) { String[] scopeParts = s.split(":"); Application application = applicationService.find(scopeParts[0]); if(application == null || (scopeParts.length > 1 && !application.hasScope(scopeParts[1]))) throw OAuthProblemException.error("invalid_scope", String.format("Invalid scope %s", s)); } }
Source:
private static void addHadoopProperties(Props props) { props.put(injectPrefix + "azkaban.flow.flowid", props.get("azkaban.flow.flowid")); props.put(injectPrefix + "azkaban.flow.execid", props.get("azkaban.flow.execid")); props.put(injectPrefix + "azkaban.job.id", props.get("azkaban.job.id")); props.put(injectPrefix + "azkaban.flow.projectname", props.get("azkaban.flow.projectname")); props.put(injectPrefix + "azkaban.flow.projectversion", props.get("azkaban.flow.projectversion")); props.put(injectPrefix + "azkaban.flow.projectlastchangeddate", props.get("azkaban.flow.projectlastchangeddate")); props.put(injectPrefix + "azkaban.flow.projectlasychangedby", props.get("azkaban.flow.projectlasychangedby")); }

Target:
private static void addHadoopProperties(Props props) { String[] propsToInject = new String[]{ CommonJobProperties.EXEC_ID, CommonJobProperties.JOB_ID, CommonJobProperties.PROJECT_NAME, CommonJobProperties.PROJECT_VERSION, CommonJobProperties.EXECUTION_LINK, CommonJobProperties.JOB_LINK, CommonJobProperties.WORKFLOW_LINK, CommonJobProperties.JOBEXEC_LINK, CommonJobProperties.ATTEMPT_LINK, CommonJobProperties.OUT_NODES, CommonJobProperties.IN_NODES, CommonJobProperties.PROJECT_LAST_CHANGED_DATE, CommonJobProperties.PROJECT_LAST_CHANGED_BY }; for(String propertyName : propsToInject) { addHadoopProperty(props, propertyName); } }
Source:
protected int processArgument(String[] args, int current) throws Exception { if (args[current].equals("-c")) bracketedOutput = false; else { if (new File(args[current]).exists()) { logger.info("Loading properties from " + args[current]); this.resourceManager = new ResourceManager(args[current]); logger.info("Completed loading properties."); } else throw new RuntimeException("The configuration file \"" + args[current] + "\" did not exist."); } return current++; }

Target:
protected int processArgument(String[] args, int current) throws Exception { if (args[current].equals("-c")) bracketedOutput = false; else { if (new File(args[current]).exists()) { System.out.println("Loading properties from " + args[current]); this.resourceManager = new ResourceManager(args[current]); System.out.println("Completed loading properties."); } else throw new RuntimeException("The configuration file \"" + args[current] + "\" did not exist."); } return current++; }
Source:
private ByteBuffer parseCBPayLoad(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; pcapPacketHeader.getInt(); long packetLength = ConversionHelper.unsignedIntToLong(blockLength); SeekableByteChannel fileChannel = getFileChannel(); if (fileChannel.size() - fileChannel.position() < packetLength) { throw new BadPcapFileException(String.format("%04x", packetLength) + " is causing buffer overrun."); } if (blockLength > Integer.MAX_VALUE) { throw new BadPcapFileException(String.format("%04x", blockLength) + " packet length is bigger than 2^31-1 bytes are not supported."); } pcapPacketData = ByteBuffer.allocate((int) packetLength - 12); pcapPacketData.clear(); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); int payLoad = fileChannel.read(pcapPacketData); if (payLoad == 0) { throw new BadPcapFileException(String.format("%04x", payLoad) + " is a bad payload."); } pcapPacketData.flip(); fileChannel.position(fileChannel.position() + blockLength - 12); return pcapPacketData; }

Target:
private ByteBuffer parseCBPayLoad(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; pcapPacketHeader.getInt(); long packetLength = ConversionHelper.unsignedIntToLong(blockLength); SeekableByteChannel fileChannel = getFileChannel(); if (fileChannel.size() - fileChannel.position() < packetLength) { throw new BadPcapFileException(String.format("0x%08x", packetLength) + " is causing buffer overrun."); } if (blockLength > Integer.MAX_VALUE) { throw new BadPcapFileException(String.format("0x%08x", blockLength) + " packet length is bigger than 2^31-1 bytes are not supported."); } pcapPacketData = ByteBuffer.allocate((int) packetLength - 12); pcapPacketData.clear(); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); int payLoad = fileChannel.read(pcapPacketData); if (payLoad == 0) { throw new BadPcapFileException(String.format("0x%08x", payLoad) + " is a bad payload."); } pcapPacketData.flip(); fileChannel.position(fileChannel.position() + blockLength - 12); return pcapPacketData; }
Source:
public final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) { Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() ); sanityCheckGroups( groups ); @SuppressWarnings("unchecked") Class<T> rootBeanClass = (Class<T>) object.getClass(); BeanMetaData<T> rootBeanMetaData = beanMetaDataManager.getBeanMetaData( rootBeanClass ); if ( !rootBeanMetaData.hasConstraints() ) { return Collections.emptySet(); } BaseBeanValidationContext<T> validationContext = getValidationContextBuilder().forValidate( rootBeanClass, rootBeanMetaData, object ); if ( !validationContext.getRootBeanMetaData().hasConstraints() ) { return Collections.emptySet(); } ValidationOrder validationOrder = determineGroupValidationOrder( groups ); BeanValueContext<?, Object> valueContext = ValueContexts.getLocalExecutionContextForBean( validatorScopedContext.getParameterNameProvider(), object, validationContext.getRootBeanMetaData(), PathImpl.createRootPath() ); return validateInContext( validationContext, valueContext, validationOrder ); }

Target:
public final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) { Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() ); sanityCheckGroups( groups ); @SuppressWarnings("unchecked") Class<T> rootBeanClass = (Class<T>) object.getClass(); BeanMetaData<T> rootBeanMetaData = beanMetaDataManager.getBeanMetaData( rootBeanClass ); if ( !rootBeanMetaData.hasConstraints() ) { return Collections.emptySet(); } BaseBeanValidationContext<T> validationContext = getValidationContextBuilder().forValidate( rootBeanClass, rootBeanMetaData, object ); ValidationOrder validationOrder = determineGroupValidationOrder( groups ); BeanValueContext<?, Object> valueContext = ValueContexts.getLocalExecutionContextForBean( validatorScopedContext.getParameterNameProvider(), object, validationContext.getRootBeanMetaData(), PathImpl.createRootPath() ); return validateInContext( validationContext, valueContext, validationOrder ); }
Source:
public Optional<Object> nextMarker() { if (totalCount < pageSize) return Optional.absent(); if (pageNumber < (totalCount / pageSize)) { return Optional.of(toPaginationOptions(pageNumber + 1)); } return Optional.absent(); }

Target:
public Optional<Object> nextMarker() { if (totalCount < pageSize) return Optional.absent(); if ((float) pageNumber < ((float) totalCount / (float) pageSize)) { return Optional.of(toPaginationOptions(pageNumber + 1)); } return Optional.absent(); }
Source:
public static void writeJobModel(JobModel jobModel, String jobModelVersion, MetadataStore metadataStore) { try { List<byte[]> jobModelSegments = chunkJobModel(jobModel); for (int jobModelSegmentIndex = 0; jobModelSegmentIndex < jobModelSegments.size(); jobModelSegmentIndex += 1) { String jobModelSegmentKey = getJobModelSegmentKey(jobModelVersion, jobModelSegmentIndex); metadataStore.put(jobModelSegmentKey, jobModelSegments.get(jobModelSegmentIndex)); } } catch (Exception e) { throw new SamzaException(String.format("Exception occurred when storing JobModel: %s with version: %s.", jobModel, jobModelVersion), e); } }

Target:
public static void writeJobModel(JobModel jobModel, String jobModelVersion, MetadataStore metadataStore) { try { String jobModelSerializedAsString = MAPPER.writeValueAsString(jobModel); byte[] jobModelSerializedAsBytes = jobModelSerializedAsString.getBytes(UTF_8); String metadataStoreKey = getJobModelKey(jobModelVersion); metadataStore.put(metadataStoreKey, jobModelSerializedAsBytes); } catch (Exception e) { throw new SamzaException(String.format("Exception occurred when storing JobModel: %s with version: %s.", jobModel, jobModelVersion), e); } }
Source:
private ConnectorTableMetadata getTableMetadata(SchemaTableName tableName) { ElasticsearchTableDescription table = client.getTable(tableName.getSchemaName(), tableName.getTableName()); if (table == null) { return null; } return new ConnectorTableMetadata(tableName, client.getColumnMetadata(table)); }

Target:
private Optional<ConnectorTableMetadata> getTableMetadata(SchemaTableName tableName) { ElasticsearchTableDescription table = client.getTable(tableName.getSchemaName(), tableName.getTableName()); if (table == null) { return Optional.empty(); } return Optional.of(new ConnectorTableMetadata(tableName, client.getColumnMetadata(table))); }
Source:
private void closeSideParts(MPart part, boolean left) { MElementContainer<MUIElement> container = getParent(part); if (container == null) return; List<MPart> others = getCloseableSideParts(part, left); closeSiblingParts(part, others, true); }

Target:
private void closeSideParts(MPart part, boolean left) { MElementContainer<MUIElement> container = getParent(part); if (container == null) { return; } List<MPart> others = getCloseableSideParts(part, left); closeSiblingParts(part, others, true); }
Source:
private IStatus createResultStatus(Object result) { if (result == null) { return new Status(IStatus.OK, InterpreterViewPlugin.PLUGIN_ID, ""); } StringBuilder message = new StringBuilder(); final String type = result.getClass().getSimpleName(); message.append(MessageFormat.format(Messages.SiriusEvaluationTask_status_resultType, type)); String size = null; if (result instanceof String) { size = String.valueOf(((String) result).length()); } else if (result instanceof Collection<?>) { size = String.valueOf(((Collection<?>) result).size()); } if (size != null) { message.append(" "); message.append(MessageFormat.format(Messages.SiriusEvaluationTask_status_resultSize, size)); } return new Status(IStatus.OK, InterpreterViewPlugin.PLUGIN_ID, message.toString()); }

Target:
private IStatus createResultStatus(Object result) { if (result == null) { return new Status(IStatus.OK, InterpreterViewPlugin.PLUGIN_ID, ""); } final String type = result.getClass().getSimpleName(); String size = null; if (result instanceof String) { size = String.valueOf(((String) result).length()); } else if (result instanceof Collection<?>) { size = String.valueOf(((Collection<?>) result).size()); } String message; if (size == null) { message = MessageFormat.format(Messages.SiriusEvaluationTask_status_resultMessage, type); } else { message = MessageFormat.format(Messages.SiriusEvaluationTask_status_sizedResultMessage, type, size); } return new Status(IStatus.OK, InterpreterViewPlugin.PLUGIN_ID, message); }
Source:
public void testBlockUseHostCpuWithPPCArch() { when(cpuFlagsManagerHandler.getCpuId(anyString(), any(Version.class))).thenReturn(CPU_ID); when(osRepository.isCpuSupported(anyInt(), any(Version.class), anyString())).thenReturn(true); doNothing().when(cmd).initTemplateDisks(); setupCanAddPpcTest(); cmd.setEffectiveCompatibilityVersion(Version.v4_0); doReturn(Collections.emptyList()).when(cmd).getImagesToCheckDestinationStorageDomains(); initPpcCluster(); doReturn(true).when(cmd).validateAddVmCommand(); doReturn(true).when(cmd).isVmNameValidLength(any(VM.class)); when(osRepository.getArchitectureFromOS(anyInt())).thenReturn(ArchitectureType.ppc64); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); cmd.getParameters().getVm().setUseHostCpuFlags(true); cmd.getParameters().getVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); cmd.getParameters().getVm().setClusterId(cluster.getId()); cmd.getParameters().getVm().setVmOs(OsType.Other.ordinal()); cmd.init(); Map<String, String> migrationMap = new HashMap<String, String>() { { put("undefined", "true"); put("x86", "true"); put("ppc", "true"); } }; mcr.mockConfigValue(ConfigValues.IsMigrationSupported, cmd.getEffectiveCompatibilityVersion(), migrationMap); ValidateTestUtils.runAndAssertValidateFailure(cmd, EngineMessage.USE_HOST_CPU_REQUESTED_ON_UNSUPPORTED_ARCH); }

Target:
public void testBlockUseHostCpuWithPPCArch() { when(cpuFlagsManagerHandler.getCpuId(anyString(), any(Version.class))).thenReturn(CPU_ID); when(osRepository.isCpuSupported(anyInt(), any(Version.class), anyString())).thenReturn(true); doNothing().when(cmd).initTemplateDisks(); setupCanAddPpcTest(); cmd.setEffectiveCompatibilityVersion(Version.v4_0); doReturn(Collections.emptyList()).when(cmd).getImagesToCheckDestinationStorageDomains(); initPpcCluster(); doReturn(true).when(cmd).validateAddVmCommand(); doReturn(true).when(cmd).isVmNameValidLength(any(VM.class)); when(osRepository.getArchitectureFromOS(anyInt())).thenReturn(ArchitectureType.ppc64); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); cmd.getParameters().getVm().setUseHostCpuFlags(true); cmd.getParameters().getVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); cmd.getParameters().getVm().setClusterId(cluster.getId()); cmd.getParameters().getVm().setVmOs(OsType.Other.ordinal()); cmd.init(); Map<String, String> migrationMap = new HashMap<>(); migrationMap.put("undefined", "true"); migrationMap.put("x86", "true"); migrationMap.put("ppc", "true"); mcr.mockConfigValue(ConfigValues.IsMigrationSupported, cmd.getEffectiveCompatibilityVersion(), migrationMap); ValidateTestUtils.runAndAssertValidateFailure(cmd, EngineMessage.USE_HOST_CPU_REQUESTED_ON_UNSUPPORTED_ARCH); }
Source:
public void removed(Provider<E> provider, E element) { Collection<E> elements = elementMap.get(provider); if (elements != null) { try { E existingElement = get(element.getUID()); onRemoveElement(existingElement); elements.remove(existingElement); notifyListenersAboutRemovedElement(element); } catch (Exception ex) { logger.warn("Could not remove element: {}", ex.getMessage(), ex); } } }

Target:
public void removed(Provider<E> provider, E element) { Collection<E> elements = elementMap.get(provider); if (elements != null) { try { E existingElement = get(element.getUID()); onRemoveElement(existingElement); elements.remove(existingElement); notifyListenersAboutRemovedElement(existingElement); } catch (Exception ex) { logger.warn("Could not remove element: {}", ex.getMessage(), ex); } } }
Source:
public void updateConditionFromEntity(boolean checkForDestruction) { final String METHOD_NAME = "updateConditionFromEntity()"; if(null != unit) { Mounted mounted = unit.getEntity().getEquipment(equipmentNum); if (!(mounted.getType() instanceof AmmoType)) { MekHQ.getLogger().log(LargeCraftAmmoBin.class, METHOD_NAME, LogLevel.WARNING, unit.getName() + " has invalid ammo bin at equipment number " + equipmentNum); } if(null != mounted && mounted.getType() instanceof AmmoType) { capacity = mounted.getAmmoCapacity(); type = mounted.getType(); if(mounted.isMissing() || mounted.isDestroyed()) { mounted.setShotsLeft(0); return; } shotsNeeded = getFullShots() - mounted.getBaseShotsLeft(); } } }

Target:
public void updateConditionFromEntity(boolean checkForDestruction) { final String METHOD_NAME = "updateConditionFromEntity()"; if(null != unit) { Mounted mounted = unit.getEntity().getEquipment(equipmentNum); if (mounted == null) { MekHQ.getLogger().log(LargeCraftAmmoBin.class, METHOD_NAME, LogLevel.WARNING, unit.getName() + " has a null Mounted at equipment number " + equipmentNum); return; } if (!(mounted.getType() instanceof AmmoType)) { MekHQ.getLogger().log(LargeCraftAmmoBin.class, METHOD_NAME, LogLevel.WARNING, unit.getName() + " has an " + mounted.getName() + " that thinks it's an ammo bin at equipment number " + equipmentNum); } else { capacity = mounted.getAmmoCapacity(); type = mounted.getType(); if(mounted.isMissing() || mounted.isDestroyed()) { mounted.setShotsLeft(0); return; } shotsNeeded = getFullShots() - mounted.getBaseShotsLeft(); } } }
Source:
public void setRequiredAttributes(List<String> requiredAttributes) { this.requiredAttributes = requiredAttributes; }

Target:
public void setRequiredAttributes(List<String> requiredAttributes) { this.requiredAttributes = new LinkedHashSet<>(); for (String entry : requiredAttributes) { if (StringUtils.isNotBlank(entry)) { this.requiredAttributes.add(entry); } } }
Source:
public byte[] getContent() { return request.getEntity() != null ? request.getEntity().toString().getBytes(Charset.forName("UTF-8")) : null; }

Target:
public byte[] getContent() { return Optional.fromNullable(request.getEntity()).transform(toStringFunction()).or("").getBytes(Charset.forName("UTF-8")); }
Source:
public void execute(IProgressMonitor monitor) throws CoreException { try { op.execute(monitor); } catch (CoreException e) { LockFailedException lockException = unwind(e); if (lockException != null) UIUtils.handleLockDelete(lockException); } }

Target:
public void execute(IProgressMonitor monitor) throws CoreException { try { op.execute(monitor); } catch (CoreException e) { LockFailedException lockException = unwind(e); if (lockException != null) UIUtils.promptToDeleteLock(lockException); else throw e; } }
Source:
public void addExecutionPlan(String executionPlan) throws RemoteException { try { eventProcessorAdminServiceStub.deployExecutionPlan(executionPlan); } catch (RemoteException e) { log.error("RemoteException", e); throw new RemoteException(e.getMessage(), e); } }

Target:
public void addExecutionPlan(String executionPlan) throws RemoteException { try { eventProcessorAdminServiceStub.deployExecutionPlan(executionPlan); } catch (RemoteException e) { log.error("RemoteException", e); throw e; } }
Source:
public EventBookingDTO createBookingOrAddToWaitingList(final IsaacEventPageDTO event, final RegisteredUserDTO user, final Map<String, String> additionalEventInformation) throws SegueDatabaseException, DuplicateBookingException { if (this.isUserBooked(event.getId(), user.getId())) { throw new DuplicateBookingException(String.format("Unable to book onto event (%s) as user (%s) is already" + " booked on to it.", event.getId(), user.getEmail())); } EventBookingDTO booking; try { this.bookingPersistenceManager.acquireDistributedLock(event.getId()); try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.CONFIRMED); } catch (EventIsFullException e) { try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.WAITING_LIST); } catch (EventIsFullException e1) { throw new RuntimeException("Creating a waiting list booking should never throw an event is full exception " + "- something went terribly wrong for this to have happened", e1); } } } finally { this.bookingPersistenceManager.releaseDistributedLock(event.getId()); } return booking; }

Target:
public EventBookingDTO createBookingOrAddToWaitingList(final IsaacEventPageDTO event, final RegisteredUserDTO user, final Map<String, String> additionalEventInformation) throws SegueDatabaseException, DuplicateBookingException { if (this.isUserBooked(event.getId(), user.getId())) { throw new DuplicateBookingException(String.format("Unable to book onto event (%s) as user (%s) is already" + " booked on to it.", event.getId(), user.getEmail())); } EventBookingDTO booking; if (EventStatus.WAITING_LIST_ONLY.equals(event.getEventStatus())) { try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.WAITING_LIST); } catch (EventIsFullException e1) { throw new RuntimeException("Creating a waiting list booking should never throw an event is full exception " + "- something went terribly wrong for this to have happened", e1); } return booking; } try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.CONFIRMED); } catch (EventIsFullException e) { try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.WAITING_LIST); } catch (EventIsFullException e1) { throw new RuntimeException("Creating a waiting list booking should never throw an event is full exception " + "- something went terribly wrong for this to have happened", e1); } } return booking; }
Source:
public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); if(BuildConfig.elementSDK) { ElementSDKManager.initElementSDK(this); } mInstance = this; if (!BuildConfig.DEBUG) { Fabric.with(this, new Crashlytics()); } else { FlowLog.setMinimumLoggingLevel(FlowLog.Level.V); } PreferencesState.getInstance().init(getApplicationContext()); FlowConfig flowConfig = new FlowConfig .Builder(this) .addDatabaseHolder(EyeSeeTeaGeneratedDatabaseHolder.class) .build(); FlowManager.init(flowConfig); initBugShaker(); }

Target:
public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); if(BuildConfig.elementSDK) { IExternalVoucherRegistry elementController = new ElementController(getApplicationContext()); InitExternalVoucherRegisterUseCase initExternalVoucherRegisterUseCase = new InitExternalVoucherRegisterUseCase(elementController); initExternalVoucherRegisterUseCase.execute(); } mInstance = this; if (!BuildConfig.DEBUG) { Fabric.with(this, new Crashlytics()); } else { FlowLog.setMinimumLoggingLevel(FlowLog.Level.V); } PreferencesState.getInstance().init(getApplicationContext()); FlowConfig flowConfig = new FlowConfig .Builder(this) .addDatabaseHolder(EyeSeeTeaGeneratedDatabaseHolder.class) .build(); FlowManager.init(flowConfig); initBugShaker(); }
Source:
@Override public GmmPartitionData build(LearningEnvironment env, Iterator<UpstreamEntry<K, V>> upstreamData, long upstreamDataSize, EmptyContext ctx) { List<LabeledVector<Double>> xs = new ArrayList<>((int)upstreamDataSize); double[][] pcxi = new double[(int)upstreamDataSize][]; int counter = 0; while (upstreamData.hasNext()) { UpstreamEntry<K, V> entry = upstreamData.next(); LabeledVector<Double> x = extractor.extract(entry.getKey(), entry.getValue()); xs.add(x); pcxi[counter] = new double[countOfComponents]; counter++; } return new GmmPartitionData(xs, pcxi); }

Target:
@Override public GmmPartitionData build(LearningEnvironment env, Iterator<UpstreamEntry<K, V>> upstreamData, long upstreamDataSize, EmptyContext ctx) { int rowsCount = Math.toIntExact(upstreamDataSize); List<LabeledVector<Double>> xs = new ArrayList<>(rowsCount); double[][] pcxi = new double[rowsCount][countOfComponents]; while (upstreamData.hasNext()) { UpstreamEntry<K, V> entry = upstreamData.next(); LabeledVector<Double> x = extractor.extract(entry.getKey(), entry.getValue()); xs.add(x); } return new GmmPartitionData(xs, pcxi); }
Source:
private Socket applySNI(final Socket socket, String hostname) { if (skipSNIApplication.get()) { LOG.log(Level.FINE, "Skipping application of SNI because IBM JDK is missing setHost() method."); return socket; } if (socket instanceof SSLSocket) { try { Method setHostMethod = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { @Override public Method run() throws NoSuchMethodException { return socket.getClass().getMethod("setHost", String.class); } }); setHostMethod.invoke(socket, hostname); LOG.log(Level.FINEST, "Applied SNI to socket for host {0}", hostname); } catch (PrivilegedActionException e) { if (e.getCause() instanceof NoSuchMethodException && Environment.IS_IBM_JAVA) { LOG.log(Level.FINE, "Failed to apply SNI to SSLSocket", e); skipSNIApplication.set(true); } else { LOG.log(Level.WARNING, "Failed to apply SNI to SSLSocket", e); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOG.log(Level.WARNING, "Failed to apply SNI to SSLSocket", e); } } return socket; }

Target:
private Socket applySNI(final Socket socket, String hostname) { if (skipSNIApplication.get()) { LOG.log(Level.FINE, "Skipping application of SNI because JDK is missing setHost() method."); return socket; } if (socket instanceof SSLSocket) { try { Method setHostMethod = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { @Override public Method run() throws NoSuchMethodException { return socket.getClass().getMethod("setHost", String.class); } }); setHostMethod.invoke(socket, hostname); LOG.log(Level.FINE, "Applied SNI to socket for host {0}", hostname); } catch (PrivilegedActionException e) { if (e.getCause() instanceof NoSuchMethodException) { Level logLevel = Environment.IS_IBM_JAVA ? Level.FINE : Level.WARNING; LOG.log(logLevel, "Failed to apply SNI to SSLSocket", e); skipSNIApplication.set(true); } else { LOG.log(Level.WARNING, "Failed to apply SNI to SSLSocket", e); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOG.log(Level.WARNING, "Failed to apply SNI to SSLSocket", e); } } return socket; }
Source:
public ActualMeterReads(final Date logTime, final long activeEnergyImport, final long activeEnergyExport, final long activeEnergyImportTariffOne, final long activeEnergyImportTariffTwo, final long activeEnergyExportTariffOne, final long activeEnergyExportTariffTwo, final ScalerUnit scalerUnit) { super(logTime, activeEnergyImport, activeEnergyExport, activeEnergyImportTariffOne, activeEnergyImportTariffTwo, activeEnergyExportTariffOne, activeEnergyExportTariffTwo); this.scalerUnit = scalerUnit; }

Target:
public ActualMeterReads(final Date logTime, final long activeEnergyImport, final long activeEnergyExport, final long activeEnergyImportTariffOne, final long activeEnergyImportTariffTwo, final long activeEnergyExportTariffOne, final long activeEnergyExportTariffTwo, final ScalerUnit scalerUnit) { super(logTime, activeEnergyImport, activeEnergyExport, activeEnergyImportTariffOne, activeEnergyImportTariffTwo, activeEnergyExportTariffOne, activeEnergyExportTariffTwo); this.scalerUnit = new ScalerUnit(scalerUnit.getDlmsUnit(), scalerUnit.getScaler()); }
Source:
public void typeProcessingOver() { if (getBooleanOption(COUNT_FRAMEWORK_BUILD_CALLS)) { System.out.printf("Found %d build() method calls.\n", numBuildCalls); } super.typeProcessingOver(); }

Target:
public void typeProcessingOver() { if (getBooleanOption(COUNT_FRAMEWORK_BUILD_CALLS)) { System.out.printf("Found %d build() method calls.%n", numBuildCalls); } super.typeProcessingOver(); }
Source:
protected int checkCommon(int[] hashes, boolean rejoining, VoltTable resultTables[], VoltMessage message, boolean txnSucceed) { if (!rejoining) { if (m_responseHashes == null) { m_responseHashes = hashes; m_txnSucceed = txnSucceed; } else if (DeterminismHash.compareHashes(m_responseHashes, hashes) >= 0) { tmLog.fatal("Stored procedure " + getStoredProcedureName() + " generated different SQL queries at different partitions." + " Shutting down to preserve data integrity."); logRelevantMismatchInformation("HASH MISMATCH", hashes, message, DeterminismHash.compareHashes(m_responseHashes, hashes)); return MISMATCH; } else if (m_txnSucceed != txnSucceed) { tmLog.fatal("Stored procedure " + getStoredProcedureName() + " succeeded on one partition but failed on another partition." + " Shutting down to preserve data integrity."); logRelevantMismatchInformation("PARTIAL ROLLBACK/ABORT", hashes, message, -1); return ABORT; } m_lastResponse = message; m_lastResultTables = resultTables; } if (m_lastResponse == null) { m_lastResponse = message; m_lastResultTables = resultTables; } m_expectedHSIds.remove(message.m_sourceHSId); if (m_expectedHSIds.size() == 0) { return DONE; } else { return WAITING; } }

Target:
protected int checkCommon(int[] hashes, boolean rejoining, VoltTable resultTables[], VoltMessage message, boolean txnSucceed) { if (!rejoining) { int pos = -1; if (m_responseHashes == null) { m_responseHashes = hashes; m_txnSucceed = txnSucceed; } else if ((pos = DeterminismHash.compareHashes(m_responseHashes, hashes)) >= 0) { tmLog.fatal("Stored procedure " + getStoredProcedureName() + " generated different SQL queries at different partitions." + " Shutting down to preserve data integrity."); logRelevantMismatchInformation("HASH MISMATCH", hashes, message, pos); return MISMATCH; } else if (m_txnSucceed != txnSucceed) { tmLog.fatal("Stored procedure " + getStoredProcedureName() + " succeeded on one partition but failed on another partition." + " Shutting down to preserve data integrity."); logRelevantMismatchInformation("PARTIAL ROLLBACK/ABORT", hashes, message, pos); return ABORT; } m_lastResponse = message; m_lastResultTables = resultTables; } if (m_lastResponse == null) { m_lastResponse = message; m_lastResultTables = resultTables; } m_expectedHSIds.remove(message.m_sourceHSId); if (m_expectedHSIds.size() == 0) { return DONE; } else { return WAITING; } }
Source:
private void openConversation(Conversation conversation, Bundle extras) { ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment); final boolean mainNeedsRefresh; if (conversationFragment == null) { mainNeedsRefresh = false; Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); if (mainFragment != null && mainFragment instanceof ConversationFragment) { conversationFragment = (ConversationFragment) mainFragment; } else { conversationFragment = new ConversationFragment(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.setCustomAnimations( R.animator.fade_bottom_in, R.animator.fade_bottom_out, R.animator.fade_bottom_in, R.animator.fade_bottom_out ); fragmentTransaction.replace(R.id.main_fragment, conversationFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } else { mainNeedsRefresh = true; } conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras); if (mainNeedsRefresh) { refreshFragment(R.id.main_fragment); } else { invalidateActionBarTitle(); } }

Target:
private void openConversation(Conversation conversation, Bundle extras) { ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment); final boolean mainNeedsRefresh; if (conversationFragment == null) { mainNeedsRefresh = false; Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); if (mainFragment != null && mainFragment instanceof ConversationFragment) { conversationFragment = (ConversationFragment) mainFragment; } else { conversationFragment = new ConversationFragment(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.setCustomAnimations( R.animator.fade_in, R.animator.fade_right_out, R.animator.fade_in, R.animator.fade_right_out ); fragmentTransaction.replace(R.id.main_fragment, conversationFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } else { mainNeedsRefresh = true; } conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras); if (mainNeedsRefresh) { refreshFragment(R.id.main_fragment); } else { invalidateActionBarTitle(); } }
Source:
public void handleEvent(Event event) { if (!initialized) { throw new RuntimeException("JmxJobMBeanManager has not been initialized"); } if (event.getRunner() instanceof JobRunner) { JobRunner jobRunner = (JobRunner) event.getRunner(); ExecutableNode node = jobRunner.getNode(); if (logger.isDebugEnabled()) { logger.info("*** got " + event.getType() + " " + node.getId() + " " + event.getRunner().getClass().getName() + " status: " + node.getStatus()); } if (event.getType() == Event.Type.JOB_STARTED) { runningJobCount.incrementAndGet(); } else if (event.getType() == Event.Type.JOB_FINISHED) { totalExecutedJobCount.incrementAndGet(); if (runningJobCount.intValue() > 0) { runningJobCount.decrementAndGet(); } else { logger.warn("runningJobCount not messed up, it is already zero " + "and we are trying to decrement on job event " + Event.Type.JOB_FINISHED); } if (node.getStatus() == Status.FAILED) { totalFailedJobCount.incrementAndGet(); } else if (node.getStatus() == Status.SUCCEEDED) { totalSucceededJobCount.incrementAndGet(); } handleJobFinishedCount(node.getStatus(), node.getType()); } } else { logger.warn("((((((((( Got a different runner: " + event.getRunner().getClass().getName()); } }

Target:
public void handleEvent(Event event) { if (!initialized) { throw new RuntimeException("JmxJobMBeanManager has not been initialized"); } if (event.getRunner() instanceof JobRunner) { JobRunner jobRunner = (JobRunner) event.getRunner(); ExecutableNode node = jobRunner.getNode(); if (logger.isDebugEnabled()) { logger.debug("*** got " + event.getType() + " " + node.getId() + " " + event.getRunner().getClass().getName() + " status: " + node.getStatus()); } if (event.getType() == Event.Type.JOB_STARTED) { runningJobCount.incrementAndGet(); } else if (event.getType() == Event.Type.JOB_FINISHED) { totalExecutedJobCount.incrementAndGet(); if (runningJobCount.intValue() > 0) { runningJobCount.decrementAndGet(); } else { logger.warn("runningJobCount not messed up, it is already zero " + "and we are trying to decrement on job event " + Event.Type.JOB_FINISHED); } if (node.getStatus() == Status.FAILED) { totalFailedJobCount.incrementAndGet(); } else if (node.getStatus() == Status.SUCCEEDED) { totalSucceededJobCount.incrementAndGet(); } handleJobFinishedCount(node.getStatus(), node.getType()); } } else { logger.warn("((((((((( Got a different runner: " + event.getRunner().getClass().getName()); } }
Source:
public void setMaskPattern(String pattern) { try { maskPattern = Pattern.compile(pattern); } catch (Exception e) { logger.error("Error to compile regex for mask pattern, will not mask anything", e); } }

Target:
public void setMaskPattern(String pattern) { try { maskPattern = Pattern.compile(pattern); } catch (Exception e) { logger.error("Error to compile regex for mask pattern, will not mask anything. Invalid pattern: " + pattern, e); } }
Source:
private GoalConflictMessage sendOrUpdateConflictMessage(PotentialConflictDTO payload, Set<Goal> conflictingGoalsOfUser, MessageDestination destination) { Date now = new Date(); Date minEndTime = new Date(now.getTime() - conflictInterval); Goal conflictingGoal = conflictingGoalsOfUser.iterator().next(); GoalConflictMessage message = cacheService.fetchLatestGoalConflictMessageForUser(payload.getLoginID(), conflictingGoal.getID(), destination, minEndTime); if (message == null || message.getEndTime().before(minEndTime)) { message = GoalConflictMessage.createInstance(payload.getLoginID(), conflictingGoal, payload.getURL()); destination.send(message); } else if (now.getTime() - message.getEndTime().getTime() >= updateSkipWindow) { assert payload.getLoginID().equals(message.getRelatedLoginID()); assert conflictingGoal.getID().equals(message.getGoal().getID()); message.setEndTime(now); } else { return message; } cacheService.updateLatestGoalConflictMessageForUser(message, destination); return message; }

Target:
private GoalConflictMessage sendOrUpdateConflictMessage(PotentialConflictDTO payload, Set<Goal> conflictingGoalsOfUser, MessageDestination destination) { Date now = new Date(); Date minEndTime = new Date(now.getTime() - conflictInterval); Goal conflictingGoal = conflictingGoalsOfUser.iterator().next(); GoalConflictMessage message = cacheService.fetchLatestGoalConflictMessageForUser(payload.getLoginID(), conflictingGoal.getID(), destination, minEndTime); if (message == null || message.getEndTime().before(minEndTime)) { message = sendNewGoalConflictMessage(payload, conflictingGoal, destination); cacheService.updateLatestGoalConflictMessageForUser(message, destination); } else if (now.getTime() - message.getEndTime().getTime() >= updateSkipWindow) { updateLastGoalConflictMessage(payload, now, conflictingGoal, message); cacheService.updateLatestGoalConflictMessageForUser(message, destination); } return message; }