auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldReturnListOfExistingNamespacesIfUserDefinedIsAllowed() throws Exception { prepareListedNamespaces( Arrays.asList( createNamespace("my-for-ws", "Active"), createNamespace("experimental", "Terminating"))); namespaceFactory = new KubernetesNamespaceFactory("predefined", "", "", null, true, clientFactory); List<KubernetesNamespaceMeta> availableNamespaces = namespaceFactory.list(); assertEquals(availableNamespaces.size(), 2); KubernetesNamespaceMeta forWS = availableNamespaces.get(0); assertEquals(forWS.getName(), "my-for-ws"); assertEquals(forWS.getAttributes().get(PHASE_ATTRIBUTE), "Active"); KubernetesNamespaceMeta experimental = availableNamespaces.get(1); assertEquals(experimental.getName(), "experimental"); assertEquals(experimental.getAttributes().get(PHASE_ATTRIBUTE), "Terminating"); }

Target:
public void shouldReturnListOfExistingNamespacesIfUserDefinedIsAllowed() throws Exception { prepareListedNamespaces( Arrays.asList( createNamespace("my-for-ws", "Active"), createNamespace("experimental", "Terminating"))); namespaceFactory = new KubernetesNamespaceFactory("predefined", "", "", null, true, clientFactory); List<KubernetesNamespaceMeta> availableNamespaces = namespaceFactory.list(); assertEquals(availableNamespaces.size(), 2); KubernetesNamespaceMeta forWS = availableNamespaces.get(0); assertEquals(forWS.getName(), "my-for-ws"); assertEquals(forWS.getAttributes().get(PHASE_ATTRIBUTE), "Active"); assertNull(forWS.getAttributes().get(DEFAULT_ATTRIBUTE)); KubernetesNamespaceMeta experimental = availableNamespaces.get(1); assertEquals(experimental.getName(), "experimental"); assertEquals(experimental.getAttributes().get(PHASE_ATTRIBUTE), "Terminating"); }
Source:
public void testDeleteLoadBalancer() throws SerializationException, StateAccessException, MappingStatusException, Rule.RuleIndexOutOfBoundsException { Router r = new Router(UUID.randomUUID(), "TENANT", "NAME", true, null, null); this.plugin.createRouter(r); Pool p = new Pool(UUID.randomUUID(), "TENANT", UUID.randomUUID(), "NAME", "TCP", "ROUND_ROBIN", true, r.id); this.plugin.createPool(p); HealthMonitor hm = new HealthMonitor(); hm.id = UUID.randomUUID(); hm.adminStateUp = true; hm.delay = 1; hm.maxRetries = 1; this.plugin.createHealthMonitor(hm); PoolHealthMonitor phm = new PoolHealthMonitor(); phm.id = hm.id; this.plugin.createPoolHealthMonitor(p.id, phm); Assert.assertTrue(this.zk.exists( pb.getPoolHealthMonitorMappingsPath(p.id, hm.id))); UUID lbId = this.dataClient.loadBalancersGetAll().get(0).getId(); this.dataClient.loadBalancerDelete(lbId); Assert.assertFalse(this.zk.exists( pb.getPoolHealthMonitorMappingsPath(p.id, hm.id))); }

Target:
public void testDeleteLoadBalancer() throws SerializationException, StateAccessException, MappingStatusException, Rule.RuleIndexOutOfBoundsException { String path = pb.getPoolHealthMonitorMappingsPath(pool.id, healthMonitor.id); Assert.assertTrue(this.zk.exists(path)); UUID lbId = this.dataClient.loadBalancersGetAll().get(0).getId(); this.dataClient.loadBalancerDelete(lbId); Assert.assertFalse(this.zk.exists(path)); }
Source:
public synchronized void releaseWakeLock() { if (wakelock != null) { wakelock.release(); wakelock = null; } }

Target:
public synchronized void releaseWakeLock() { if (wakelock != null && wakelock.isHeld()) { wakelock.release(); } wakelock = null; }
Source:
public ArrayList<Sequence> getToBeKeptFromArrayList(ArrayList<Sequence> sequences) { ArrayList<Sequence> deletableSequences = new ArrayList<Sequence>(); for (Sequence s : sequences) { if (s.getType().equals(Sequence.TYPE_BEGIN_QUESTIONNAIRE) ) { deletableSequences.add(s); } } return deletableSequences; }

Target:
public ArrayList<Sequence> getToBeKeptFromArrayList(ArrayList<Sequence> sequences) { ArrayList<Sequence> toBeKeptQuestionnaires = new ArrayList<Sequence>(); for (Sequence s : sequences) { if (s.getType().equals(Sequence.TYPE_BEGIN_QUESTIONNAIRE) ) { toBeKeptQuestionnaires.add(s); } } return toBeKeptQuestionnaires; }
Source:
public List<MetadataValue> getMetadata(Item item, String schema, String element, String qualifier, String lang) { if (StringUtils.equals(schema, "relation") && !StringUtils.equals(element, "type")) { List<MetadataValue> relationMetadata = getRelationshipMetadata(item, false); List<MetadataValue> listToReturn = new LinkedList<>(); for (MetadataValue metadataValue : relationMetadata) { if (StringUtils.equals(metadataValue.getMetadataField().getElement(), element)) { listToReturn.add(metadataValue); } } return listToReturn; } else { List<MetadataValue> dbMetadataValues = super.getMetadata(item, schema, element, qualifier, lang); if (!(StringUtils.equals(schema, "*") && StringUtils.equals(element, "*") && StringUtils.equals(qualifier, "*") && StringUtils.equals(lang, "*"))) { return dbMetadataValues; } List<MetadataValue> fullMetadataValueList = getRelationshipMetadata(item, true); fullMetadataValueList.addAll(dbMetadataValues); return fullMetadataValueList; } }

Target:
public List<MetadataValue> getMetadata(Item item, String schema, String element, String qualifier, String lang) { if (StringUtils.equals(schema, MetadataSchemaEnum.RELATION.getName()) && !StringUtils.equals(element, "type")) { List<MetadataValue> relationMetadata = getRelationshipMetadata(item, false); List<MetadataValue> listToReturn = new LinkedList<>(); for (MetadataValue metadataValue : relationMetadata) { if (StringUtils.equals(metadataValue.getMetadataField().getElement(), element)) { listToReturn.add(metadataValue); } } return listToReturn; } else { List<MetadataValue> dbMetadataValues = super.getMetadata(item, schema, element, qualifier, lang); if (!(StringUtils.equals(schema, "*") && StringUtils.equals(element, "*") && StringUtils.equals(qualifier, "*") && StringUtils.equals(lang, "*"))) { return dbMetadataValues; } List<MetadataValue> fullMetadataValueList = getRelationshipMetadata(item, true); fullMetadataValueList.addAll(dbMetadataValues); return fullMetadataValueList; } }
Source:
private static StepVideoThumbnail parseVideoThumbnail(JSONObject jVideoThumb) throws JSONException { String guid = jVideoThumb.getString("guid"); int imageid = jVideoThumb.getInt("imageid"); String ratio = jVideoThumb.getString("ratio"); int width = jVideoThumb.getInt("width"); int height = jVideoThumb.getInt("height"); String url = jVideoThumb.getString("medium"); url = url.substring(0, url.lastIndexOf(".")); Log.w("StepVideoThumbnail URL:", " >>> " + url); return new StepVideoThumbnail(guid, imageid, url, ratio, width, height); }

Target:
private static StepVideoThumbnail parseVideoThumbnail(JSONObject jVideoThumb) throws JSONException { String guid = jVideoThumb.getString("guid"); int imageid = jVideoThumb.getInt("imageid"); String ratio = jVideoThumb.getString("ratio"); int width = jVideoThumb.getInt("width"); int height = jVideoThumb.getInt("height"); String url = jVideoThumb.getString("medium"); url = url.substring(0, url.lastIndexOf(".")); return new StepVideoThumbnail(guid, imageid, url, ratio, width, height); }
Source:
public void testUpdateFeed_AddMoreItems() { DocumentFile documentFile1 = DocumentFile.fromFile(localFeedDir1); try (MockedStatic<DocumentFile> dfMock = Mockito.mockStatic(DocumentFile.class)) { dfMock.when(() -> DocumentFile.fromTreeUri(any(), any())).thenReturn(documentFile1); Feed feed = new Feed(FEED_URL, null); LocalFeedUpdater.updateFeed(feed, context); } DocumentFile documentFile2 = DocumentFile.fromFile(localFeedDir2); try (MockedStatic<DocumentFile> dfMock = Mockito.mockStatic(DocumentFile.class)) { dfMock.when(() -> DocumentFile.fromTreeUri(any(), any())).thenReturn(documentFile2); Feed feed = new Feed(FEED_URL, null); LocalFeedUpdater.updateFeed(feed, context); } List<Feed> feedListAfter = DBReader.getFeedList(); assertEquals(1, feedListAfter.size()); Feed feedAfter = feedListAfter.get(0); List<FeedItem> feedItems = DBReader.getFeedItemList(feedAfter); assertEquals(2, feedItems.size()); }

Target:
public void testUpdateFeed_AddMoreItems() { callUpdateFeed(LOCAL_FEED_DIR1); callUpdateFeed(LOCAL_FEED_DIR2); verifySingleFeedInDatabaseAndItemCount(2); }
Source:
public void startStripe(InputStreamSources dictionaryStreamSources, List<ColumnEncoding> encodings) throws IOException { presentStreamSource = missingStreamSource(BooleanInputStream.class); inMapStreamSources.clear(); valueStreamDescriptors.clear(); valueStreamReaders.clear(); ColumnEncoding encoding = encodings.get(baseValueStreamDescriptor.getStreamId()); Map<Integer, DwrfSequenceEncoding> additionalSequenceEncodings = encoding.getAdditionalSequenceEncodings().orElse(Collections.emptyMap()); for (int sequence : additionalSequenceEncodings.keySet()) { inMapStreamSources.add(missingStreamSource(BooleanInputStream.class)); StreamDescriptor valueStreamDescriptor = copyStreamDescriptorWithSequence(baseValueStreamDescriptor, sequence); valueStreamDescriptors.add(valueStreamDescriptor); StreamReader valueStreamReader = StreamReaders.createStreamReader(valueStreamDescriptor, hiveStorageTimeZone, systemMemoryContext); valueStreamReader.startStripe(dictionaryStreamSources, encodings); valueStreamReaders.add(valueStreamReader); } keyBlockTemplate = getKeyBlockTemplate(additionalSequenceEncodings.values()); readOffset = 0; nextBatchSize = 0; presentStream = null; rowGroupOpen = false; }

Target:
public void startStripe(InputStreamSources dictionaryStreamSources, List<ColumnEncoding> encodings) throws IOException { presentStreamSource = missingStreamSource(BooleanInputStream.class); inMapStreamSources.clear(); valueStreamDescriptors.clear(); valueStreamReaders.clear(); ColumnEncoding encoding = encodings.get(baseValueStreamDescriptor.getStreamId()); Map<Integer, DwrfSequenceEncoding> additionalSequenceEncodings = encoding.getAdditionalSequenceEncodings().orElse(Collections.emptySortedMap()); for (int sequence : additionalSequenceEncodings.keySet()) { inMapStreamSources.add(missingStreamSource(BooleanInputStream.class)); StreamDescriptor valueStreamDescriptor = copyStreamDescriptorWithSequence(baseValueStreamDescriptor, sequence); valueStreamDescriptors.add(valueStreamDescriptor); StreamReader valueStreamReader = StreamReaders.createStreamReader(valueStreamDescriptor, hiveStorageTimeZone, systemMemoryContext); valueStreamReader.startStripe(dictionaryStreamSources, encodings); valueStreamReaders.add(valueStreamReader); } keyBlockTemplate = getKeyBlockTemplate(additionalSequenceEncodings.values()); readOffset = 0; nextBatchSize = 0; presentStream = null; rowGroupOpen = false; }
Source:
public JsonResponse addUserToGroup(@PathVariable long userID, @PathVariable long groupID){ try { JCUser jcUser = userService.get(userID); jcUser.addGroup(groupService.get(groupID)); userService.updateUser(jcUser); return new JsonResponse(JsonResponseStatus.SUCCESS); } catch (Exception e) { return new JsonResponse(JsonResponseStatus.FAIL); } }

Target:
public JsonResponse addUserToGroup(@PathVariable long userID, @PathVariable long groupID){ try { long forumId = componentService.getComponentOfForum().getId(); userService.addUserToGroup(forumId, userID, groupID); return new JsonResponse(JsonResponseStatus.SUCCESS); } catch (Exception e) { return new JsonResponse(JsonResponseStatus.FAIL); } }
Source:
private AlgorithmOptions.Builder buildOptions(GHMatrixRequest request, GraphHopper hopper){ String algoStr = request.getAlgorithm().isEmpty() ? MatrixAlgorithm.OneToOneLoop : request.getAlgorithm(); TraversalMode tMode; String tModeStr = request.getHints().get("traversal_mode", TraversalMode.NODE_BASED.toString()); try { tMode = TraversalMode.fromString(tModeStr); } catch (Exception ex) { throw new IllegalStateException("Invalid TraversalMode"); } FlagEncoder encoder = hopper.getEncodingManager().getEncoder(request.getVehicle()); RoutingAlgorithmFactory tmpAlgoFactory = hopper.getAlgorithmFactory(request.getHints()); Weighting weighting; if (hopper.getCHFactoryDecorator().isEnabled()) { if (tmpAlgoFactory instanceof PrepareContractionHierarchies){ weighting = ((PrepareContractionHierarchies) tmpAlgoFactory).getWeighting(); }else { throw new IllegalStateException("Although CH was enabled a non-CH algorithm factory was returned " + tmpAlgoFactory); } } else weighting = hopper.createWeighting(request.getHints(), encoder); int maxVisitedNodes = Integer.MAX_VALUE; int maxVisistedNodesForRequest = request.getHints().getInt("routing.maxVisitedNodes", maxVisitedNodes); if (maxVisistedNodesForRequest > maxVisitedNodes) { throw new IllegalStateException("The routing.maxVisitedNodes parameter has to be below or equal to:" + maxVisitedNodes); } return AlgorithmOptions.start(). algorithm(algoStr) .traversalMode(tMode) .flagEncoder(encoder) .weighting(weighting) .maxVisitedNodes(maxVisistedNodesForRequest) .hints(request.getHints()); }

Target:
private AlgorithmOptions.Builder buildOptions(GHMatrixRequest request, GraphHopper hopper){ String algoStr = request.getAlgorithm().isEmpty() ? MATRIX_ONE_TO_ONE : request.getAlgorithm(); TraversalMode tMode; String tModeStr = request.getHints().get("traversal_mode", TraversalMode.NODE_BASED.toString()); try { tMode = TraversalMode.fromString(tModeStr); } catch (Exception ex) { throw new IllegalStateException("Invalid TraversalMode"); } FlagEncoder encoder = hopper.getEncodingManager().getEncoder(request.getVehicle()); RoutingAlgorithmFactory tmpAlgoFactory = hopper.getAlgorithmFactory(request.getHints()); Weighting weighting; if (hopper.getCHFactoryDecorator().isEnabled()) { if (tmpAlgoFactory instanceof PrepareContractionHierarchies){ weighting = ((PrepareContractionHierarchies) tmpAlgoFactory).getWeighting(); }else { throw new IllegalStateException("Although CH was enabled a non-CH algorithm factory was returned " + tmpAlgoFactory); } } else weighting = hopper.createWeighting(request.getHints(), encoder); int maxVisitedNodes = Integer.MAX_VALUE; int maxVisistedNodesForRequest = request.getHints().getInt("routing.maxVisitedNodes", maxVisitedNodes); if (maxVisistedNodesForRequest > maxVisitedNodes) { throw new IllegalStateException("The routing.maxVisitedNodes parameter has to be below or equal to:" + maxVisitedNodes); } return AlgorithmOptions.start(). algorithm(algoStr) .traversalMode(tMode) .flagEncoder(encoder) .weighting(weighting) .maxVisitedNodes(maxVisistedNodesForRequest) .hints(request.getHints()); }
Source:
public String translate(final Case aCase) { String elseString = ""; if (aCase.getFalseAction() != null) { inject(aCase.getFalseAction()); elseString = String.format("ELSE %s", aCase.getFalseAction().translate()); } return String.format("CASE %s %s END", aCase.whens.stream() .peek(this::inject) .map(When::translate) .collect(Collectors.joining(" ")), elseString); }

Target:
public String translate(final Case aCase) { String elseString = ""; if (aCase.getFalseAction() != null) { inject(aCase.getFalseAction()); elseString = String.format("ELSE %s", aCase.getFalseAction().translate()); } final String whens = aCase.whens.stream() .peek(this::inject) .map(When::translate) .collect(Collectors.joining(" ")); return String.format("CASE %s %s END", whens, elseString); }
Source:
public void refreshCustomizedViewMap(final HelixDataAccessor accessor) { List<String> stateTypes = accessor.getChildNames(accessor.keyBuilder().customizedViews()); if (_propertyDataChangedMap.get(HelixConstants.ChangeType.CUSTOMIZED_VIEW).getAndSet(false)) { for (String stateType: stateTypes) { _customizedViewCacheMap.get(stateType).refresh(accessor); } } for (String stateType : _customizedViewCacheMap.keySet()) { if (!stateTypes.contains(stateType)) { logger.info("Remove customizedView for state: " + stateType); _customizedViewCacheMap.remove(stateType); } } }

Target:
public void refreshCustomizedViewMap(final HelixDataAccessor accessor) { List<String> newStateTypes = accessor.getChildNames(accessor.keyBuilder().customizedViews()); if (_propertyDataChangedMap.get(HelixConstants.ChangeType.CUSTOMIZED_VIEW).getAndSet(false)) { for (String stateType : newStateTypes) { if (!_customizedViewCacheMap.containsKey(stateType)) { CustomizedViewCache newCustomizedViewCache = new CustomizedViewCache(getClusterName(), stateType); _customizedViewCacheMap.put(stateType, newCustomizedViewCache); } _customizedViewCacheMap.get(stateType).refresh(accessor); } Set<String> previousCachedStateTypes = _customizedViewCacheMap.keySet(); previousCachedStateTypes.removeAll(newStateTypes); logger.info("Remove customizedView for state: " + previousCachedStateTypes); removeCustomizedViewTypes(new ArrayList<>(previousCachedStateTypes)); } }
Source:
public String getDisplayName(int tokenType) { if (tokenType >= Token.MIN_USER_TOKEN_TYPE && tokenType < displayNames.length) { String displayName = displayNames[tokenType]; if (displayName != null) { return displayName; } } String literalName = getLiteralName(tokenType); if (literalName != null) { return literalName; } String symbolicName = getSymbolicName(tokenType); if (symbolicName != null) { return symbolicName; } return Integer.toString(tokenType); }

Target:
public String getDisplayName(int tokenType) { if (tokenType >= 0 && tokenType < displayNames.length) { String displayName = displayNames[tokenType]; if (displayName != null) { return displayName; } } String literalName = getLiteralName(tokenType); if (literalName != null) { return literalName; } String symbolicName = getSymbolicName(tokenType); if (symbolicName != null) { return symbolicName; } return Integer.toString(tokenType); }
Source:
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) { if ( !roundEnvironment.processingOver() ) { RoundContext roundContext = new RoundContext( annotationProcessorContext ); Set<TypeElement> deferredMappers = getAndResetDeferredMappers(); processMapperElements( deferredMappers, roundContext ); Set<TypeElement> mappers = getMappers( annotations, roundEnvironment ); processMapperElements( mappers, roundContext ); } else if ( !deferredMappers.isEmpty() ) { for ( DeferredMapper deferredMapper : deferredMappers ) { TypeElement deferredMapperElement = deferredMapper.deferredMapperElement; Element erroneousElement = deferredMapper.erroneousElement; String erroneousElementName; if ( erroneousElement instanceof QualifiedNameable ) { erroneousElementName = ( (QualifiedNameable) erroneousElement ).getQualifiedName().toString(); } else { erroneousElementName = erroneousElement.getSimpleName().toString(); } processingEnv.getMessager() .printMessage( Kind.ERROR, "No implementation was created for " + deferredMapperElement.getSimpleName() + " due to having a problem in the type hierarchy with " + erroneousElementName, deferredMapperElement ); } } return ANNOTATIONS_CLAIMED_EXCLUSIVELY; }

Target:
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) { if ( !roundEnvironment.processingOver() ) { RoundContext roundContext = new RoundContext( annotationProcessorContext ); Set<TypeElement> deferredMappers = getAndResetDeferredMappers(); processMapperElements( deferredMappers, roundContext ); Set<TypeElement> mappers = getMappers( annotations, roundEnvironment ); processMapperElements( mappers, roundContext ); } else if ( !deferredMappers.isEmpty() ) { for ( DeferredMapper deferredMapper : deferredMappers ) { TypeElement deferredMapperElement = deferredMapper.deferredMapperElement; Element erroneousElement = deferredMapper.erroneousElement; String erroneousElementName; if ( erroneousElement instanceof QualifiedNameable ) { erroneousElementName = ( (QualifiedNameable) erroneousElement ).getQualifiedName().toString(); } else { erroneousElementName = erroneousElement.getSimpleName().toString(); } deferredMapperElement = annotationProcessorContext.getElementUtils() .getTypeElement( deferredMapperElement.getQualifiedName() ); processingEnv.getMessager() .printMessage( Kind.ERROR, "No implementation was created for " + deferredMapperElement.getSimpleName() + " due to having a problem in the erroneous element " + erroneousElementName + "." + " Hint: this often means that some other annotation processor was supposed to" + " process the erroneous element. You can also enable MapStruct verbose mode by setting" + " -Amapstruct.verbose=true as a compilation argument.", deferredMapperElement ); } } return ANNOTATIONS_CLAIMED_EXCLUSIVELY; }
Source:
public void handleSchemes(Collection<IScheme> toAdd, Collection<IScheme> toRemove) throws Exception { List<ISchemeInformation> schemesInformation = getSchemesInformation(toAdd); for (ISchemeInformation schemeInformation : schemesInformation) { String handlerInstanceLocation = schemeInformation.getHandlerInstanceLocation(); processExecutor.execute(LSREGISTER, UNREGISTER, handlerInstanceLocation); } String pathToEclipseApp = getPathToEclipseApp(); changePlistFile(toAdd, toRemove, pathToEclipseApp); registerAppWithLsregister(pathToEclipseApp); }

Target:
public void handleSchemes(Collection<IScheme> toAdd, Collection<IScheme> toRemove) throws Exception { String pathToEclipseApp = getPathToEclipseApp(); changePlistFile(toAdd, toRemove, pathToEclipseApp); registerAppWithLsregister(pathToEclipseApp); }
Source:
public GetQuotaByQuotaIdQueryParameters(Guid quotaId) { this(); this.quotaId = quotaId; }

Target:
public GetQuotaByQuotaIdQueryParameters(Guid quotaId) { this.quotaId = quotaId; }
Source:
public void doPatchsetCreatedHook(final Change change, final PatchSet patchSet) { final PatchSetCreatedEvent event = new PatchSetCreatedEvent(); event.change = getChangeAttribute(change); event.patchSet = getPatchSetAttribute(patchSet); fireEvent(change, event); final List<String> args = new ArrayList<String>(); args.add(patchsetCreatedHook.getAbsolutePath()); args.add("--change"); args.add(event.change.id); args.add("--change-number"); args.add(event.change.number); args.add("--project"); args.add(event.change.project); args.add("--branch"); args.add(event.change.branch); args.add("--commit"); args.add(event.patchSet.revision); args.add("--patchset"); args.add(event.patchSet.number); runHook(getRepo(change), args); }

Target:
public void doPatchsetCreatedHook(final Change change, final PatchSet patchSet) { final PatchSetCreatedEvent event = new PatchSetCreatedEvent(); event.change = getChangeAttribute(change); event.patchSet = getPatchSetAttribute(patchSet); fireEvent(change, event); final List<String> args = new ArrayList<String>(); args.add(patchsetCreatedHook.getAbsolutePath()); args.add("--change"); args.add(event.change.id); args.add("--change-url"); args.add(event.change.url); args.add("--project"); args.add(event.change.project); args.add("--branch"); args.add(event.change.branch); args.add("--commit"); args.add(event.patchSet.revision); args.add("--patchset"); args.add(event.patchSet.number); runHook(getRepo(change), args); }
Source:
private NSArray selectionsFromBindings() { if (canGetValueForBinding(Keys.Selections)) { NSArray result = (NSArray)valueForBinding(Keys.Selections); if (hasBinding(Keys.SortKey)) { String sortKey = stringValueForBinding(Keys.SortKey); result = ERXArrayUtilities.sortedArraySortedWithKey(result, sortKey); } if(result != null) { return result; } } return NSArray.EmptyArray; }

Target:
private NSArray selectionsFromBindings() { if (canGetValueForBinding(Keys.Selections)) { NSArray result = (NSArray)valueForBinding(Keys.Selections); if(result != null) { if (hasBinding(Keys.SortKey)) { String sortKey = stringValueForBinding(Keys.SortKey); result = ERXArrayUtilities.sortedArraySortedWithKey(result, sortKey); } return result; } } return NSArray.EmptyArray; }
Source:
public LocalStreamProcessorListener(String processorId) { if (processorId == null) { throw new NullPointerException("processorId cannot be null in LocalStreamProcessorListener!!"); } this.processorId = processorId; }

Target:
public LocalStreamProcessorListener(String processorId) { if (StringUtils.isEmpty(processorId)) { throw new NullPointerException("processorId has to be defined in LocalStreamProcessorListener."); } this.processorId = processorId; }
Source:
public void testSocketSourceGenerator() throws Exception { final ExecutorService serverExecutor = Executors.newSingleThreadExecutor(); final List<String> inputStream = Arrays.asList( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "In in leo nec erat fringilla mattis eu non massa.", "Cras quis diam suscipit, commodo enim id, pulvinar nunc."); final List<String> result = new LinkedList<>(); final ServerSocket serverSoc = serverSocket; serverExecutor.submit(() -> { try { final Socket sc = serverSoc.accept(); System.out.println("Socket is connected to " + sc); final PrintWriter out = new PrintWriter(sc.getOutputStream(), true); inputStream.stream().forEach(out::println); out.close(); sc.close(); } catch (final IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }); final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); jcb.bindNamedParameter(SocketServerIp.class, "127.0.0.1"); jcb.bindNamedParameter(SocketServerPort.class, "8030"); jcb.bindImplementation(SourceGenerator.class, TextSocketStreamGenerator.class); final Injector injector = Tang.Factory.getTang().newInjector(jcb.build()); final SourceGenerator<String> sourceGenerator = injector.getInstance(SourceGenerator.class); sourceGenerator.setOutputEmitter(result::add); sourceGenerator.start(); Thread.sleep(3000); sourceGenerator.close(); Assert.assertEquals("SourceGenerator should generate " + inputStream, inputStream, result); }

Target:
public void testSocketSourceGenerator() throws Exception { final List<String> inputStream = Arrays.asList( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "In in leo nec erat fringilla mattis eu non massa.", "Cras quis diam suscipit, commodo enim id, pulvinar nunc."); final CountDownLatch countDownLatch = new CountDownLatch(inputStream.size()); final ExecutorService serverExecutor = Executors.newSingleThreadExecutor(); final List<String> result = new LinkedList<>(); serverExecutor.submit(() -> { try { final Socket socket = serverSocket.accept(); LOG.info("Socket is connected to " + socket); final PrintWriter out = new PrintWriter(socket.getOutputStream(), true); inputStream.stream().forEach(out::println); out.close(); socket.close(); } catch (final IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }); final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); jcb.bindNamedParameter(SocketServerIp.class, serverIpAddress); jcb.bindNamedParameter(SocketServerPort.class, Integer.toString(port)); jcb.bindImplementation(SourceGenerator.class, TextSocketStreamGenerator.class); final Injector injector = Tang.Factory.getTang().newInjector(jcb.build()); try (final SourceGenerator<String> sourceGenerator = injector.getInstance(SourceGenerator.class)) { sourceGenerator.setOutputEmitter((data) -> { result.add(data); countDownLatch.countDown(); }); sourceGenerator.start(); countDownLatch.await(); } finally { Assert.assertEquals("SourceGenerator should generate " + inputStream, inputStream, result); } }
Source:
public void testInterceptResolve() throws IOException { String pathAfterResolution = "/user-hadoop"; Path remainingPath = new Path("/ad-data"); String srcRegex = "hadoop"; String replaceString = "hdfs"; RegexMountPointResolvedDstPathReplaceInterceptor interceptor = new RegexMountPointResolvedDstPathReplaceInterceptor(srcRegex, replaceString); interceptor.initialize(); Assert.assertTrue( interceptor.interceptResolvedDestPathStr(pathAfterResolution) .equals("/user-hdfs")); }

Target:
public void testInterceptResolve() throws IOException { String pathAfterResolution = "/user-hadoop"; String srcRegex = "hadoop"; String replaceString = "hdfs"; RegexMountPointResolvedDstPathReplaceInterceptor interceptor = new RegexMountPointResolvedDstPathReplaceInterceptor(srcRegex, replaceString); interceptor.initialize(); Assert.assertEquals("/user-hdfs", interceptor.interceptResolvedDestPathStr(pathAfterResolution)); }
Source:
public void testAdaptForTable(){ GCRule gcRule = GCRULES.maxVersions(1); ColumnFamily columnFamily = ColumnFamily.newBuilder() .setGcRule(gcRule.toProto()).build(); Table table = Table.fromProto(com.google.bigtable.admin.v2.Table.newBuilder() .setName(TABLE_NAME) .putColumnFamilies(COLUMN_FAMILY, columnFamily).build()); HTableDescriptor actualTableDesc = tableAdapter.adapt(table); HTableDescriptor expected = new HTableDescriptor(TableName.valueOf(TABLE_ID)); expected.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); Assert.assertEquals(expected, actualTableDesc); }

Target:
public void testAdaptForTable(){ GCRule gcRule = GCRULES.maxVersions(1); ColumnFamily columnFamily = ColumnFamily.newBuilder() .setGcRule(gcRule.toProto()).build(); Table table = Table.newBuilder() .setName(TABLE_NAME) .putColumnFamilies(COLUMN_FAMILY, columnFamily).build(); HTableDescriptor actualTableDesc = tableAdapter.adapt( com.google.cloud.bigtable.admin.v2.models.Table.fromProto(table)); HTableDescriptor expected = new HTableDescriptor(TableName.valueOf(TABLE_ID)); expected.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); Assert.assertEquals(expected, actualTableDesc); }
Source:
public void deployContrib(String name, String contrib) throws Exception { RuntimeContext context = runtime.getContext(name); if (context == null) { context = runtime.getContext(); BundleFile file = lookupBundle(name); URL location = file.getEntry(contrib); if (location == null) { throw new AssertionError("Cannot locate " + contrib + " in " + name); } context.deploy(location); return; } context.deploy(contrib); }

Target:
public void deployContrib(String name, String contrib) throws Exception { RuntimeContext context = runtime.getContext(name); if (context == null) { context = runtime.getContext(); BundleFile file = lookupBundle(name); URL location = file.getEntry(contrib); if (location == null) { throw new AssertionError("Cannot locate " + contrib + " in " + name); } context.deploy(location); } else { context.deploy(contrib); } }
Source:
private synchronized void populateFromDbHelper(Map<Long, ResourceGroupSpecBuilder> recordMap, Set<Long> rootGroupIds, Map<Long, ResourceGroupIdTemplate> resourceGroupIdTemplateMap, Map<Long, Set<Long>> subGroupIdsToBuild) { List<ResourceGroupSpecBuilder> records = dao.getResourceGroups(nodeInfo.getEnvironment()); records.stream() .forEach(record -> { recordMap.put(record.getId(), record); if (!record.getParentId().isPresent()) { rootGroupIds.add(record.getId()); resourceGroupIdTemplateMap.put(record.getId(), new ResourceGroupIdTemplate(record.getNameTemplate().toString())); } else { subGroupIdsToBuild.computeIfAbsent(record.getParentId().get(), k -> new HashSet<>()).add(record.getId()); } }); }

Target:
private synchronized void populateFromDbHelper(Map<Long, ResourceGroupSpecBuilder> recordMap, Set<Long> rootGroupIds, Map<Long, ResourceGroupIdTemplate> resourceGroupIdTemplateMap, Map<Long, Set<Long>> subGroupIdsToBuild) { List<ResourceGroupSpecBuilder> records = dao.getResourceGroups(nodeInfo.getEnvironment()); for (ResourceGroupSpecBuilder record : records) { recordMap.put(record.getId(), record); if (!record.getParentId().isPresent()) { rootGroupIds.add(record.getId()); resourceGroupIdTemplateMap.put(record.getId(), new ResourceGroupIdTemplate(record.getNameTemplate().toString())); } else { subGroupIdsToBuild.computeIfAbsent(record.getParentId().get(), k -> new HashSet<>()).add(record.getId()); } } }
Source:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("url", url) .append("username", username) .append("originType", originType) .append("vmsNames", vmsNames); }

Target:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("url", url) .append("username", username) .append("originType", originType) .append("namesOfVms", namesOfVms); }
Source:
public void prohibitedCustomHeaderFails() throws Exception { CouchConfig customCouchConfig = getCouchConfig(); Map<String, String> customHeaders = new HashMap<String, String>(); customHeaders.put("WWW-Authenticate", "test"); customCouchConfig.setCustomHeaders(customHeaders); HttpRequests client = new CouchClient(customCouchConfig, TEST_DB).getHttpClient(); URI allDbUri = this.uriHelper.allDbsUri(); InputStream is = client.get(allDbUri); Assert.assertNotNull(is); String s = IOUtils.toString(is); Assert.assertTrue(s.contains(TEST_DB)); }

Target:
public void prohibitedCustomHeaderFails() throws Exception { String[] prohibitedHeaders = {"WWW-Authenticate", "Host", "Connection", "Content-Type", "Accept", "Content-Length"}; for (String h : prohibitedHeaders) { try { CouchConfig customCouchConfig = getCouchConfig(); Map<String, String> customHeaders = new HashMap<String, String>(); customHeaders.put(h, "test"); customCouchConfig.setCustomHeaders(customHeaders); HttpRequests client = new CouchClient(customCouchConfig, TEST_DB).getHttpClient(); URI allDbUri = this.uriHelper.allDbsUri(); client.get(allDbUri); Assert.fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException iae) { ; } } }
Source:
private boolean isArgValueIdentifierTerminator(char ch, boolean quoteOpen) { return (ch == '|' && !quoteOpen) || (ch == ';' && !quoteOpen) || ch == '\0' || (ch == ' ' && !quoteOpen) || (ch == '\t' && !quoteOpen) || (ch == '>' && !quoteOpen) || ch == '\r' || ch == '\n'; }

Target:
private boolean isArgValueIdentifierTerminator(char ch, boolean quoteOpen) { return (ch == '&' && !quoteOpen) || (ch == '|' && !quoteOpen) || (ch == ';' && !quoteOpen) || ch == '\0' || (ch == ' ' && !quoteOpen) || (ch == '\t' && !quoteOpen) || (ch == '>' && !quoteOpen) || ch == '\r' || ch == '\n'; }
Source:
private static StringBuilder fakeBody(final Request... parts) throws IOException { final StringBuilder builder = new StringBuilder(); for (final Request part : parts) { builder.append( String.format("--%s", FakeMultipartRequest.BOUNDARY) ) .append(RqMultipart.CRLF) .append("Content-Disposition: ") .append( new RqHeaders.Smart( new RqHeaders.Base(part) ).single("Content-Disposition") ).append(RqMultipart.CRLF); final String body = new RqPrint(part).printBody(); if (!(RqMultipart.CRLF.equals(body) || body.isEmpty())) { builder.append(RqMultipart.CRLF) .append(body) .append(RqMultipart.CRLF); } } builder.append("Content-Transfer-Encoding: utf-8") .append(RqMultipart.CRLF) .append( String.format("--%s--", FakeMultipartRequest.BOUNDARY) ); return builder; }

Target:
private static StringBuilder fakeBody(final Request... parts) throws IOException { final StringBuilder builder = new StringBuilder(100); for (final Request part : parts) { builder.append( String.format("--%s", FakeMultipartRequest.BOUNDARY) ) .append(RqMultipart.CRLF) .append(RqMultipart.DISPOSITION) .append(": ") .append( new RqHeaders.Smart( new RqHeaders.Base(part) ).single(RqMultipart.DISPOSITION) ).append(RqMultipart.CRLF); final String body = new RqPrint(part).printBody(); if (!(RqMultipart.CRLF.equals(body) || body.isEmpty())) { builder.append(RqMultipart.CRLF) .append(body) .append(RqMultipart.CRLF); } } builder.append("Content-Transfer-Encoding: utf-8") .append(RqMultipart.CRLF) .append( String.format("--%s--", FakeMultipartRequest.BOUNDARY) ); return builder; }
Source:
public Integer call() throws Exception { try { Iterator<RemoteStore> storeIterator = stores.iterator(); if (storeIterator.hasNext()) { RemoteStore store = storeIterator.next(); RemoteCache<Object, Object> storeCache = store.getRemoteCache(); RemoteStoreConfiguration storeConfig = store.getConfiguration(); if (!storeConfig.hotRodWrapping()) { throw log.remoteStoreNoHotRodWrapping(cache.getName()); } AtomicInteger counter = new AtomicInteger(0); migrateEntriesWithMetadata(storeCache,counter); gracefulShutdown(executorService); return counter.intValue(); } return null; } finally { cache.removeListener(listener); } }

Target:
public Integer call() throws Exception { try { Iterator<RemoteStore> storeIterator = stores.iterator(); if (storeIterator.hasNext()) { RemoteStore store = storeIterator.next(); RemoteCache<Object, Object> storeCache = store.getRemoteCache(); RemoteStoreConfiguration storeConfig = store.getConfiguration(); if (!storeConfig.hotRodWrapping()) { throw log.remoteStoreNoHotRodWrapping(cache.getName()); } AtomicInteger counter = new AtomicInteger(0); migrateEntriesWithMetadata(storeCache, counter); awaitTermination(executorService); return counter.intValue(); } return null; } finally { cache.removeListener(listener); if (executorService != null) { executorService.shutdownNow(); } } }
Source:
public void testAddFileWithOutOfRangeKey(){ List<S3ObjectSummary> list = Arrays.asList(badKeyFile); manger.addS3Objects(list.iterator(), mockCallback); verify(mockCallback).progressMade(null); verify(mockFileMetadataDao, never()).getFileState(badKeyFile.getBucketName(), badKeyFile.getKey()); verify(mockFolderMetadataDao, never()).createOrUpdateFolderState((FolderState) any()); }

Target:
public void testAddFileWithOutOfRangeKey(){ List<S3ObjectSummary> list = Arrays.asList(outOfRangeKeyFile); manger.addS3Objects(list.iterator(), mockCallback); verify(mockCallback).progressMade(null); verify(mockFileMetadataDao, never()).getFileState(outOfRangeKeyFile.getBucketName(), outOfRangeKeyFile.getKey()); verify(mockFolderMetadataDao, never()).createOrUpdateFolderState((FolderState) any()); }
Source:
public String toString() { String prefix = DISCONTINUE == getAction() ? "DC " : ""; return prefix + "DrugOrder(" + getDose() + getDoseUnits() + " of " + (getDrugNonCoded() != null ? getDrugNonCoded() : (getDrug() != null ? getDrug().getName() : "[no drug]")) + " from " + getDateActivated() + " to " + (isDiscontinuedRightNow() ? getDateStopped() : getAutoExpireDate()) + ")"; }

Target:
public String toString() { String prefix = DISCONTINUE == getAction() ? "DC " : ""; return prefix + "DrugOrder(" + getDose() + getDoseUnits() + " of " + (isNonCodedDrug() ? getDrugNonCoded() : (getDrug() != null ? getDrug().getName() : "[no drug]")) + " from " + getDateActivated() + " to " + (isDiscontinuedRightNow() ? getDateStopped() : getAutoExpireDate()) + ")"; }
Source:
private void setUpAccessBaseAgingExpectations() { ReferenceQueue<Integer> queue = mock(ReferenceQueue.class); map = new ReapedMap<String, Integer>(1000, true, queue); when(queue.poll()).thenReturn(null); }

Target:
private void setUpAccessBaseAgingExpectations() { ReferenceQueue<Integer> queue = mock(ReferenceQueue.class); map = new ReapedMap<String, Integer>(1000, true, queue); }
Source:
public Vote[] getPredictionVotes() { double trueValue = this.lastSeenInstance.classValue(); return new Vote[] { new Vote("instance number", this.instanceIdentifier), new Vote("true value", trueValue, 10), new Vote("predicted value", this.lastPredictedValue, 10) }; }

Target:
public Vote[] getPredictionVotes() { double trueValue = this.lastSeenInstance.classValue(); return new Vote[] { new Vote("instance number", this.instanceIdentifier), new Vote("true value", trueValue, this.DECIMAL_PLACES), new Vote("predicted value", this.lastPredictedValue, this.DECIMAL_PLACES) }; }
Source:
protected DispatchRequest doExecute() { super.doExecute(); try { RequestBuilder requestBuilder = buildRequest(); return new GwtHttpDispatchRequest(requestBuilder.send()); } catch (RequestException | ActionException e) { onExecuteFailure(e); } return new CompletedDispatchRequest(); }

Target:
protected DispatchRequest doExecute() { try { RequestBuilder requestBuilder = buildRequest(); return new GwtHttpDispatchRequest(requestBuilder.send()); } catch (RequestException | ActionException e) { onExecuteFailure(e); } return new CompletedDispatchRequest(); }
Source:
public void emptyRegexValidationFails(){ SpamRuleDto spamRuleDto = randomSpamRuleDto().setRegex(""); Set<ConstraintViolation<SpamRuleDto>> constraintViolations = validator.validate(spamRuleDto); Assert.assertEquals(constraintViolations.size(), 1); }

Target:
public void emptyRegexValidationFails(){ SpamRuleDto spamRuleDto = randomSpamRuleDto().setRegex(nullOrEmpty()); Set<ConstraintViolation<SpamRuleDto>> constraintViolations = validator.validate(spamRuleDto); assertEquals(constraintViolations.size(), 1); }
Source:
protected IgniteAwareApplication() { Runtime.getRuntime().addShutdownHook(hook = new Thread(() -> { log.info("SIGTERM recorded."); if (!finished && !broken) terminate(); else log.info("Application already done [finished=" + finished + ", broken=" + broken + "]"); log.info("Waiting for graceful termination..."); while (!finished && !broken) { if (log.isTraceEnabled()) log.trace("Waiting for graceful termination cycle..."); try { U.sleep(100); } catch (IgniteInterruptedCheckedException e) { e.printStackTrace(); } } log.info("Graceful termination done."); })); log.info("ShutdownHook registered."); }

Target:
protected IgniteAwareApplication() { Runtime.getRuntime().addShutdownHook(hook = new Thread(() -> { log.info("SIGTERM recorded."); if (!finished && !broken) terminate(); else log.info("Application already done [finished=" + finished + ", broken=" + broken + "]"); if (log.isDebugEnabled()) log.debug("Waiting for graceful termination..."); while (!finished && !broken) { log.info("Waiting for graceful termination cycle..."); try { U.sleep(100); } catch (IgniteInterruptedCheckedException e) { e.printStackTrace(); } } if (log.isDebugEnabled()) log.debug("Graceful termination done."); })); log.info("ShutdownHook registered."); }
Source:
private Vector createOrcVector(TajoDataTypes.DataType type) { switch (type.getType()) { case INT1: case INT2: case INT4: case INT8: case UINT1: case UINT2: case UINT4: case UINT8: case INET4: case TIMESTAMP: case DATE: return new LongVector(); case FLOAT4: case FLOAT8: return new DoubleVector(); case BOOLEAN: case NULL_TYPE: return new BooleanVector(); case BLOB: case TEXT: case CHAR: case PROTOBUF: return new SliceVector(); default: throw new UnsupportedException("This data type is not supported currently: "+type.toString()); } }

Target:
private Vector createOrcVector(TajoDataTypes.DataType type) { switch (type.getType()) { case INT1: case INT2: case INT4: case INT8: case INET4: case TIMESTAMP: case DATE: return new LongVector(); case FLOAT4: case FLOAT8: return new DoubleVector(); case BOOLEAN: case NULL_TYPE: return new BooleanVector(); case BLOB: case TEXT: case CHAR: case PROTOBUF: return new SliceVector(); default: LOG.error("Not supported type for "+type.toString()); throw new UnimplementedException("ORC type: "+type.toString()); } }
Source:
public void execute(final AsyncResponse asyncResponse, final String id, final String details, final String command, String kwargs, final int timeout) { final InstrumentAgent thisAgent = discovery.getAgent(id); if (thisAgent != null) { if (kwargs == null) kwargs = "{}"; final String myKwargs = kwargs; executor.execute(new Runnable() { @Override public void run() { try { ClusterTask ct = ClusterLockUtils.lookupLock(id, details); if (ct != null) { ClusterTaskPK id = ct.getId(); log.handle(Priority.INFO, "ID name = " + id.getName() + " Details = " + id.getDetails() + " locked = " + ct.isRunning()); if (!ct.isRunning()) { String reply = thisAgent.execute(command, myKwargs, timeout); asyncResponse.resume(Response.ok(reply).type(MediaType.APPLICATION_JSON).build()); } else { asyncResponse.resume(Response.ok("Can't execute " + command + ". ID = " + id.getName() + " is locked", MediaType.APPLICATION_JSON).build()); } } else { log.handle(Priority.INFO, "LockUtils lookupLock returns null for Cluster Task"); asyncResponse.resume(Response.ok("LockUtils lookupLock returns null Cluster Task", MediaType.APPLICATION_JSON).build()); } } catch (Exception e) { log.error("ClusterLockUtils.lookupLock exception", e); asyncResponse.resume(Response.ok("ClusterLockUtils.lookupLock exception", MediaType.APPLICATION_JSON).build()); } } }); } else { asyncResponse.resume(agentNotFound()); } }

Target:
public void execute(final AsyncResponse asyncResponse, final String id, final String details, final String command, String kwargs, final int timeout) { final InstrumentAgent thisAgent = discovery.getAgent(id); if (thisAgent != null) { if (kwargs == null) kwargs = "{}"; final String myKwargs = kwargs; executor.execute(new Runnable() { @Override public void run() { try { ClusterTask ct = ClusterLockUtils.lookupLock(id, details); if (ct != null) { ClusterTaskPK id = ct.getId(); log.handle(Priority.INFO, "ID name = " + id.getName() + " Details = " + id.getDetails() + " locked = " + ct.isRunning()); if (!ct.isRunning()) { String reply = thisAgent.execute(command, myKwargs, timeout); asyncResponse.resume(Response.ok(reply).type(MediaType.APPLICATION_JSON).build()); } else { asyncResponse.resume(Response.ok("Can't execute " + command + ". ID = " + id.getName() + " is locked", MediaType.APPLICATION_JSON).build()); } } else { log.handle(Priority.INFO, "Error processing lock lookup for cluster task [" + id + "/" + details + "]"); asyncResponse.resume(Response.ok("Error processing lock lookup for cluster task [" + id + "/" + details + "]", MediaType.APPLICATION_JSON).build()); } } catch (Exception e) { log.error("Error Processing lock lookup for cluster task [" + id + "/" + details + "]", e); asyncResponse.resume(Response.ok("Error Processing lock lookup for cluster task [" + id + "/" + details + "]", MediaType.APPLICATION_JSON).build()); } } }); } else { asyncResponse.resume(agentNotFound()); } }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Record["); builder.append("id=").append(id); builder.append(", ").append("name=").append(name); builder.append(", ").append("type=").append(type); if (ttl != null) builder.append(", ").append("ttl=").append(ttl); if (data != null) builder.append(", ").append("data=").append(data); if (priority != null) builder.append(", ").append("priority=").append(priority); builder.append("]"); return builder.toString(); }

Target:
public String toString() { return new StringBuilder(name).append(type).append(ttl).append(data).append(priority).toString(); }
Source:
void testNewTargetGroupsWithEmptyUnitsAndEnemyUnits() { final List<TargetGroup> result = TargetGroup.newTargetGroups(List.of(), List.of()); assertEquals(0, result.size()); }

Target:
void testNewTargetGroupsWithEmptyUnitsAndEnemyUnits() { final List<TargetGroup> result = TargetGroup.newTargetGroups(List.of(), List.of()); assertThat(result, empty()); }
Source:
public String listSenders(final Model model) { HashMap<Sender, Boolean> optInRequiredSenders = new HashMap<>(); Sender.all().stream() .filter(Sender_Base::getOptInRequired) .filter(sender -> sender.getRecipients().stream().anyMatch(group -> group.isMember(Authenticate.getUser()))) .forEach(sender -> optInRequiredSenders.put(sender, sender.getOptedInUsers().contains(Authenticate.getUser()))); final boolean isOptOutAvailable = MessagingSystem.getInstance().getOptOutAvailable().isMember(Authenticate.getUser()); model.addAttribute("isOptOutAvailable", isOptOutAvailable); if (isOptOutAvailable) { model.addAttribute("isOptedOut", MessagingSystem.getInstance().getOptedOutGroup().isMember(Authenticate.getUser())); } model.addAttribute("optInRequiredSenders", optInRequiredSenders); return "/messaging/listOptIns"; }

Target:
public String listSenders(final Model model) { HashMap<Sender, Boolean> optInRequiredSenders = new HashMap<>(); Sender.all().stream() .filter(Sender_Base::getOptInRequired) .filter(sender -> sender.getRecipients().stream().anyMatch(group -> group.isMember(Authenticate.getUser()))) .forEach(sender -> optInRequiredSenders.put(sender, sender.getOptedInUsers().contains(Authenticate.getUser()))); final boolean canConfigOptOut = MessagingSystem.getInstance().getOptOutAvailable().isMember(Authenticate.getUser()) || MessagingSystem.getInstance().getOptedOutGroup().isMember(Authenticate.getUser()); model.addAttribute("canConfigOptOut", canConfigOptOut); if (canConfigOptOut) { model.addAttribute("isOptedOut", MessagingSystem.getInstance().getOptedOutGroup().isMember(Authenticate.getUser())); } model.addAttribute("optInRequiredSenders", optInRequiredSenders); return "/messaging/listOptIns"; }