auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void executeCommand() { getParameters().setEntityInfo(new EntityInfo(VdcObjectType.VmTemplate, getVmTemplateId())); setSucceeded(true); if (images != null && !images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(getVmTemplateId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); }

Target:
protected void executeCommand() { getParameters().setEntityInfo(new EntityInfo(VdcObjectType.VmTemplate, getVmTemplateId())); setSucceeded(true); if (images != null && !images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(getVmTemplateId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } TransactionSupport.executeInNewTransaction(() -> { vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); return null; }); }
Source:
public void testReleaseValidation() throws VersionValidationException { ArtifactCoordinates coordinates1 = new NugetHierarchicalArtifactCoordinates(); coordinates1.setVersion("1"); ArtifactCoordinates coordinates2 = new NugetHierarchicalArtifactCoordinates(); coordinates2.setVersion("1.0"); ArtifactCoordinates coordinates3 = new NugetHierarchicalArtifactCoordinates(); coordinates3.setVersion("1.0-RELEASE"); try { validator.validate(repository, coordinates1); validator.validate(repository, coordinates2); validator.validate(repository, coordinates3); } catch (Exception ex) { fail("Validator should not throw any exception but received " + ExceptionUtils.getStackTrace(ex)); } }

Target:
public void testReleaseValidation() throws VersionValidationException { ArtifactCoordinates coordinates1 = new NugetHierarchicalArtifactCoordinates(); coordinates1.setVersion("1"); ArtifactCoordinates coordinates2 = new NugetHierarchicalArtifactCoordinates(); coordinates2.setVersion("1.0"); ArtifactCoordinates coordinates3 = new NugetHierarchicalArtifactCoordinates(); coordinates3.setVersion("1.0-rc-1"); ArtifactCoordinates coordinates4 = new NugetHierarchicalArtifactCoordinates(); coordinates4.setVersion("1.0-milestone-1"); ArtifactCoordinates coordinates5 = new NugetHierarchicalArtifactCoordinates(); coordinates5.setVersion("1.0-alpha-1"); ArtifactCoordinates coordinates6 = new NugetHierarchicalArtifactCoordinates(); coordinates6.setVersion("1.0-beta-1"); try { validator.validate(repository, coordinates1); validator.validate(repository, coordinates2); validator.validate(repository, coordinates3); validator.validate(repository, coordinates4); validator.validate(repository, coordinates5); validator.validate(repository, coordinates6); } catch (Exception ex) { fail("Validator should not throw any exception but received " + ExceptionUtils.getStackTrace(ex)); } }
Source:
public static void createSubscription( String topic, String subscriptionName, String owner) throws RegistryClientException { if(log.isDebugEnabled()){ log.debug("Topic name going to put to the registry is: " + topic + "and subscription name for the topic in the registry is: " + subscriptionName); } if(!NameValidations.isValidTopicName(topic)) { throw new RegistryClientException("\nTopic name: " + NameValidations.getTopicNameWithoutTenantDomain(topic) + " can contain only alphanumeric characters and star(*) " + "delimited by dots. Names can ends with any of these or, with '#' "); } try { RegistryService registryService = CommonsDataHolder.getInstance().getRegistryService(); UserRegistry registry = registryService.getGovernanceSystemRegistry( CarbonContext.getThreadLocalCarbonContext().getTenantId() <= 0 ? MultitenantConstants.SUPER_TENANT_ID : CarbonContext.getThreadLocalCarbonContext().getTenantId() ); Collection subscription; String tenantBasedTopicName = getTenantBasedTopicName(topic); String subscriptionID = CommonsUtil.getSubscriptionID(tenantBasedTopicName, subscriptionName); if (!registry.resourceExists(subscriptionID)) { subscription = registry.newCollection(); } else { subscription = (Collection) registry.get(subscriptionID); } subscription.setProperty(OWNER, owner); subscription.setProperty(NAME, subscriptionName); subscription.setProperty(CREATED_TIME, ConverterUtil.convertToString(new Date())); registry.put(subscriptionID, subscription); } catch (RegistryException e) { throw new RegistryClientException(e); } }

Target:
public static void createSubscription( String topic, String subscriptionName, String owner) throws RegistryClientException { if (log.isDebugEnabled()) { log.debug("Saving topic name: \"" + topic + "\" in registry, and subscription name for this topic is: " + subscriptionName); } try { RegistryService registryService = CommonsDataHolder.getInstance().getRegistryService(); UserRegistry registry = registryService.getGovernanceSystemRegistry( CarbonContext.getThreadLocalCarbonContext().getTenantId() <= 0 ? MultitenantConstants.SUPER_TENANT_ID : CarbonContext.getThreadLocalCarbonContext().getTenantId() ); Collection subscription; String tenantBasedTopicName = getTenantBasedTopicName(topic); String subscriptionID = CommonsUtil.getSubscriptionID(tenantBasedTopicName, subscriptionName); if (!registry.resourceExists(subscriptionID)) { subscription = registry.newCollection(); } else { subscription = (Collection) registry.get(subscriptionID); } subscription.setProperty(OWNER, owner); subscription.setProperty(NAME, subscriptionName); subscription.setProperty(CREATED_TIME, ConverterUtil.convertToString(new Date())); registry.put(subscriptionID, subscription); } catch (RegistryException e) { throw new RegistryClientException(e); } }
Source:
public static RuleStatusInfo create(RuleStatus status) { if(status == null) { throw new IllegalArgumentException("Status must not be null."); } switch (status) { case DISABLED: return RuleStatusInfo.DISABLED; case UNINITIALIZED: return RuleStatusInfo.UNINITIALIZED; case INITIALIZING: return RuleStatusInfo.INITIALIZING; case IDLE: return RuleStatusInfo.IDLE; case TRIGGERED: return RuleStatusInfo.TRIGGERED; case RUNNING: return RuleStatusInfo.RUNNING; } throw new IllegalArgumentException("Invalid status value."); }

Target:
public static RuleStatusInfo create(RuleStatus status) { if (status == null) { throw new IllegalArgumentException("Status must not be null."); } switch (status) { case DISABLED: return RuleStatusInfo.DISABLED; case UNINITIALIZED: return RuleStatusInfo.UNINITIALIZED; case INITIALIZING: return RuleStatusInfo.INITIALIZING; case IDLE: return RuleStatusInfo.IDLE; case TRIGGERED: return RuleStatusInfo.TRIGGERED; case RUNNING: return RuleStatusInfo.RUNNING; default: throw new IllegalArgumentException("Invalid status value."); } }
Source:
public void index(DbSession dbSession, Collection<EsQueueDto> items) { if (items.isEmpty()) { return; } List<String> logins = items .stream() .filter(i -> { requireNonNull(i.getDocUuid(), () -> "BUG - " + i + " has not been persisted before indexing"); return true; }) .map(EsQueueDto::getDocUuid) .collect(toArrayList()); ListMultimap<String, String> organizationUuidsByLogin = ArrayListMultimap.create(); dbClient.organizationMemberDao().selectForUserIndexing(dbSession, logins, organizationUuidsByLogin::put); BulkIndexer bulkIndexer = newBulkIndexer(Size.REGULAR); bulkIndexer.start(dbSession, items); dbClient.userDao().scrollByLogins(dbSession, logins, u -> bulkIndexer.add(newIndexRequest(u, organizationUuidsByLogin))); bulkIndexer.stop(); }

Target:
public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) { if (items.isEmpty()) { return new IndexingResult(); } Set<String> logins = items .stream() .filter(i -> { requireNonNull(i.getDocId(), () -> "BUG - " + i + " has not been persisted before indexing"); return i.getDocType() == EsQueueDto.Type.USER; }) .map(EsQueueDto::getDocId) .collect(toHashSet(items.size())); ListMultimap<String, String> organizationUuidsByLogin = ArrayListMultimap.create(); dbClient.organizationMemberDao().selectForUserIndexing(dbSession, logins, organizationUuidsByLogin::put); BulkIndexer bulkIndexer = newBulkIndexer(Size.REGULAR, new ResiliencyIndexingListener(dbClient, dbSession, items)); bulkIndexer.start(); dbClient.userDao().scrollByLogins(dbSession, logins, u -> { logins.remove(u.getLogin()); bulkIndexer.add(newIndexRequest(u, organizationUuidsByLogin)); }); logins.forEach(l -> bulkIndexer.addDeletion(UserIndexDefinition.INDEX_TYPE_USER, l)); return bulkIndexer.stop(); }
Source:
public static boolean preValidate(String path) throws CTFException { String metadataPath = path + Utils.SEPARATOR + METADATA_FILENAME; File metadataFile = new File(metadataPath); if (metadataFile.exists() && metadataFile.length() > PREVALIDATION_SIZE) { try (FileChannel fc = FileChannel.open(metadataFile.toPath(), StandardOpenOption.READ)) { ByteBuffer bb = ByteBuffer.allocate(PREVALIDATION_SIZE); fc.read(bb); if (bb.getInt(0) == Utils.TSDL_MAGIC) { return true; } bb.order(ByteOrder.LITTLE_ENDIAN); if (bb.getInt(0) == Utils.TSDL_MAGIC) { return true; } bb.position(0); Charset forName = Charset.forName("ASCII"); byte bytes[] = new byte[PREVALIDATION_SIZE]; bb.get(bytes); String text = new String(bytes, forName); return text.startsWith(TEXT_ONLY_METADATA_HEADER_PREFIX); } catch (IOException e) { throw new CTFException(e.getMessage(), e); } } return false; }

Target:
public static boolean preValidate(String path) throws CTFException { String metadataPath = path + Utils.SEPARATOR + METADATA_FILENAME; File metadataFile = new File(metadataPath); if (metadataFile.exists() && metadataFile.length() > PREVALIDATION_SIZE) { try (FileChannel fc = FileChannel.open(metadataFile.toPath(), StandardOpenOption.READ)) { ByteBuffer bb = ByteBuffer.allocate(PREVALIDATION_SIZE); bb.clear(); fc.read(bb); bb.flip(); if (bb.getInt(0) == Utils.TSDL_MAGIC) { return true; } bb.order(ByteOrder.LITTLE_ENDIAN); if (bb.getInt(0) == Utils.TSDL_MAGIC) { return true; } bb.position(0); Charset forName = Charset.forName("ASCII"); byte bytes[] = new byte[PREVALIDATION_SIZE]; bb.get(bytes); String text = new String(bytes, forName); return text.startsWith(TEXT_ONLY_METADATA_HEADER_PREFIX); } catch (IOException e) { throw new CTFException(e.getMessage(), e); } } return false; }
Source:
public static Slice concatenate(Slice a, byte[] b) { int size = a.length + b.length; byte[] bytes = new byte[size]; System.arraycopy(a, a.offset, bytes, 0, a.length); System.arraycopy(b, 0, bytes, a.length, b.length); return new Slice(bytes); }

Target:
public static Slice concatenate(Slice a, byte[] b) { int size = a.length + b.length; byte[] bytes = new byte[size]; System.arraycopy(a.buffer, a.offset, bytes, 0, a.length); System.arraycopy(b, 0, bytes, a.length, b.length); return new Slice(bytes); }
Source:
public void cancelTimeout( Value request ) { tasks.remove( request.strValue() ); }

Target:
public Boolean cancelTimeout( Value request ) { long timeoutId = request.longValue(); ScheduledFuture f = scheduledFutureHashMap.remove( timeoutId ); return f != null && f.cancel( false ); }
Source:
private void createBuilderInjectionMethod(Element element, EFragmentHolder holder, BundleHelper bundleHelper, JFieldVar argKeyStaticField, String fieldName) { JDefinedClass builderClass = holder.getBuilderClass(); JFieldRef builderArgsField = holder.getBuilderArgsField(); TypeMirror type = codeModelHelper.getActualType(element, holder); JClass paramClass = codeModelHelper.typeMirrorToJClass(type); JMethod method = builderClass.method(PUBLIC, holder.narrow(builderClass), fieldName); JExpression arg = method.param(paramClass, fieldName); if (bundleHelper.isParcelerBean()) { arg = getCodeModel().ref("org.parceler.Parcels").staticInvoke("wrap").arg(arg); } method.body().invoke(builderArgsField, bundleHelper.getMethodNameToSave()).arg(argKeyStaticField).arg(arg); method.body()._return(_this()); String docComment = getProcessingEnvironment().getElementUtils().getDocComment(element); codeModelHelper.addTrimmedDocComment(method, docComment); method.javadoc().addParam(fieldName).append("the Fragment argument"); method.javadoc().addReturn().append("the FragmentBuilder to chain calls"); }

Target:
private void createBuilderInjectionMethod(Element element, EFragmentHolder holder, BundleHelper bundleHelper, JFieldVar argKeyStaticField, String fieldName) { JDefinedClass builderClass = holder.getBuilderClass(); JFieldRef builderArgsField = holder.getBuilderArgsField(); TypeMirror type = codeModelHelper.getActualType(element, holder); AbstractJClass paramClass = codeModelHelper.typeMirrorToJClass(type); JMethod method = builderClass.method(PUBLIC, holder.narrow(builderClass), fieldName); JVar arg = method.param(paramClass, fieldName); method.body().add(bundleHelper.getExpressionToSaveFromField(builderArgsField, argKeyStaticField, arg)); method.body()._return(_this()); String docComment = getProcessingEnvironment().getElementUtils().getDocComment(element); codeModelHelper.addTrimmedDocComment(method, docComment); method.javadoc().addParam(fieldName).append("the Fragment argument"); method.javadoc().addReturn().append("the FragmentBuilder to chain calls"); }
Source:
private static void importFilter(SWTBotView viewBot) { try { File tempFile = File.createTempFile("test", ".xml"); FileWriter fw = new FileWriter(tempFile); try (BufferedWriter bw = new BufferedWriter(fw)) { bw.write(FILTER); } TmfFileDialogFactory.setOverrideFiles(tempFile.getAbsolutePath()); } catch (IOException e) { fail("Failed to add a filter"); } viewBot.toolbarButton("Import filters").click(); WaitUtils.waitUntil(count -> count > 0, viewBot.bot().tree(0).rowCount(), "Failed to import test filter"); }

Target:
private static void importFilter(SWTBotView viewBot) { try { File tempFile = File.createTempFile("test", ".xml"); FileWriter fw = new FileWriter(tempFile); try (BufferedWriter bw = new BufferedWriter(fw)) { bw.write(FILTER); } TmfFileDialogFactory.setOverrideFiles(tempFile.getAbsolutePath()); } catch (IOException e) { fail("Failed to add a filter"); } viewBot.toolbarButton("Import filters").click(); WaitUtils.waitUntil(tree -> tree.rowCount() > 0, viewBot.bot().tree(0), "Failed to import test filter"); }
Source:
public SAMFileWriter makeBAMWriter(final SAMFileHeader header, final boolean presorted, final Path outputPath, final int compressionLevel) { try { final boolean createMd5File = this.createMd5File && IOUtil.isRegularPath(outputPath); if (this.createMd5File && !createMd5File) { log.warn("Cannot create MD5 file for BAM because output file is not a regular file: " + outputPath.toUri()); } OutputStream os = IOUtil.maybeBufferOutputStream(Files.newOutputStream(outputPath), bufferSize); if (createMd5File) os = new Md5CalculatingOutputStream(os, IOUtil.addExtension(outputPath,".md5")); final BAMFileWriter ret = new BAMFileWriter(os, outputPath.toString(), compressionLevel, deflaterFactory); final boolean createIndex = this.createIndex && IOUtil.isRegularPath(outputPath); if (this.createIndex && !createIndex) { log.warn("Cannot create index for BAM because output file is not a regular file: " + outputPath.toUri()); } if (this.tmpDir != null) ret.setTempDirectory(this.tmpDir); initializeBAMWriter(ret, header, presorted, createIndex); if (this.useAsyncIo) return new AsyncSAMFileWriter(ret, this.asyncOutputBufferSize); else return ret; } catch (final IOException ioe) { throw new RuntimeIOException("Error opening file: " + outputPath.toUri()); } }

Target:
public SAMFileWriter makeBAMWriter(final SAMFileHeader header, final boolean presorted, final Path outputPath, final int compressionLevel) { try { final boolean createMd5File = this.createMd5File && IOUtil.isRegularPath(outputPath); if (this.createMd5File && !createMd5File) { log.warn("Cannot create MD5 file for BAM because output file is not a regular file: " + outputPath.toUri()); } OutputStream os = IOUtil.maybeBufferOutputStream(Files.newOutputStream(outputPath), bufferSize); if (createMd5File) os = new Md5CalculatingOutputStream(os, IOUtil.addExtension(outputPath,".md5")); final BAMFileWriter ret = new BAMFileWriter(os, outputPath.toUri().toString(), compressionLevel, deflaterFactory); final boolean createIndex = this.createIndex && IOUtil.isRegularPath(outputPath); if (this.createIndex && !createIndex) { log.warn("Cannot create index for BAM because output file is not a regular file: " + outputPath.toUri()); } initializeBAMWriter(ret, header, presorted, createIndex); if (this.useAsyncIo) return new AsyncSAMFileWriter(ret, this.asyncOutputBufferSize); else return ret; } catch (final IOException ioe) { throw new RuntimeIOException("Error opening file: " + outputPath.toUri()); } }
Source:
public static WordVectors loadStaticModel(InputStream inputStream) throws IOException { File tmpFile = DL4JFileUtils.createTempFile("word2vec"+System.currentTimeMillis(), "tmp"); tmpFile.deleteOnExit(); FileUtils.copyInputStreamToFile(inputStream, tmpFile); return loadStaticModel(tmpFile); }

Target:
public static WordVectors loadStaticModel(InputStream inputStream) throws IOException { File tmpFile = DL4JFileUtils.createTempFile("word2vec"+System.currentTimeMillis(), "tmp"); FileUtils.copyInputStreamToFile(inputStream, tmpFile); try { return loadStaticModel(tmpFile); } finally { tmpFile.delete(); } }
Source:
private void removeWidgetFromUI(WidgetToShow widget) { final Tab tab = widgets2Tabs.remove(widget); if (tab != null) { final int removedTabIndex = tabsPanel.getWidgetIndex(tab); tabsPanel.remove(tab); widgetsPanel.remove(widget.getWidget()); tabs2Widgets.remove(tab); final MenuItemWidget listItemWidget = widgets2ListItems.remove(widget); if (listItemWidget != null) { menu.removeListItem(listItemWidget); } if (tab == selectedTab) { if (tabsPanel.getWidgetCount() > 1) { Widget widgetToSelect; if (removedTabIndex < tabsPanel.getWidgetCount() - 1) { widgetToSelect = tabsPanel.getWidget(removedTabIndex); } else { widgetToSelect = tabsPanel.getWidget(tabsPanel.getWidgetCount() - 2); } if (widgetToSelect instanceof Tab) { selectTab((Tab) widgetToSelect); onTabClicked((Tab) widgetToSelect); } } } } }

Target:
private void removeWidgetFromUI(WidgetToShow widget) { final Tab tab = widgets2Tabs.remove(widget); if (tab != null) { final int removedTabIndex = tabsPanel.getWidgetIndex(tab); tabsPanel.remove(tab); widgetsPanel.remove(widget.getWidget()); tabs2Widgets.remove(tab); final MenuItemWidget listItemWidget = widgets2ListItems.remove(widget); if (listItemWidget != null) { menu.removeListItem(listItemWidget); } if (tab == selectedTab && tabsPanel.getWidgetCount() > 1) { Widget widgetToSelect; if (removedTabIndex < tabsPanel.getWidgetCount() - 1) { widgetToSelect = tabsPanel.getWidget(removedTabIndex); } else { widgetToSelect = tabsPanel.getWidget(tabsPanel.getWidgetCount() - 2); } if (widgetToSelect instanceof Tab) { selectTab((Tab) widgetToSelect); onTabClicked((Tab) widgetToSelect); } } } }
Source:
public void shouldErrorOutWhenPluginDoesNotAgentSupportStatusReport() { final Capabilities capabilities = new Capabilities(true, false); final GoPluginDescriptor descriptor = new GoPluginDescriptor("cd.go.example.plugin", null, null, null, null, false); elasticAgentMetadataStore.setPluginInfo(new ElasticAgentPluginInfo(descriptor, null, null, null, capabilities)); thrown.expect(RuntimeException.class); thrown.expectMessage("Plugin does not support agent status report."); service.getAgentStatusReport("cd.go.example.plugin", null, null); }

Target:
public void shouldErrorOutWhenPluginDoesNotAgentSupportStatusReport() { final Capabilities capabilities = new Capabilities(true, false); final GoPluginDescriptor descriptor = new GoPluginDescriptor("cd.go.example.plugin", null, null, null, null, false); elasticAgentMetadataStore.setPluginInfo(new ElasticAgentPluginInfo(descriptor, null, null, null, capabilities)); thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("Plugin does not support agent status report."); service.getAgentStatusReport("cd.go.example.plugin", null, null); }
Source:
private final Object decodeOne(final String field, final String string, final VCFCompoundHeaderLine format) { try { if ( string.equals(VCFConstants.MISSING_VALUE_v4) ) return null; else { switch ( format.getType() ) { case Character: return string; case Flag: final boolean b = Boolean.valueOf(string) || string.equals("1"); if ( b == false ) throw new TribbleException("VariantContext FLAG fields " + field + " cannot contain false values" + " as seen at " + getContig() + ":" + getStart()); return b; case String: return string; case Integer: return Integer.valueOf(string); case Float: return Double.parseDouble(string); default: throw new TribbleException("Unexpected type for field" + field); } } } catch (NumberFormatException e) { throw new TribbleException("Could not decode field " + field + " with value " + string + " of declared type " + format.getType()); } }

Target:
private final Object decodeOne(final String field, final String string, final VCFCompoundHeaderLine format) { try { if ( string.equals(VCFConstants.MISSING_VALUE_v4) ) return null; else { switch ( format.getType() ) { case Character: return string; case Flag: final boolean b = Boolean.valueOf(string) || string.equals("1"); if ( b == false ) throw new TribbleException("VariantContext FLAG fields " + field + " cannot contain false values" + " as seen at " + getContig() + ":" + getStart()); return b; case String: return string; case Integer: return Integer.valueOf(string); case Float: return VCFUtils.parseVcfDouble(string); default: throw new TribbleException("Unexpected type for field" + field); } } } catch (NumberFormatException e) { throw new TribbleException("Could not decode field " + field + " with value " + string + " of declared type " + format.getType()); } }
Source:
private String makeRowNumbers(final Issue issue) { StringBuilder builder = new StringBuilder(); Iterator<Integer> iterator = issue.getRowNumbers().iterator(); while (iterator.hasNext()) { builder.append(iterator.next()); if (iterator.hasNext()) { builder.append(", "); } } return builder.toString(); }

Target:
private String makeRowNumbers(final Issue issue) { return issue.getRowNumbers() .stream() .map(Object::toString) .collect(Collectors.joining(", ")); }
Source:
public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { JdbcOutputTableHandle handle = jdbcClient.beginCreateTable(tableMetadata); finishCreateTable(session, handle, emptyList(), emptyList()); }

Target:
public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { jdbcClient.createTable(tableMetadata); }
Source:
public List<String> getDCFromExpression(String expression) { Set<String> DC = new HashSet<String>(); Matcher m; ArrayList<String> patterns = new ArrayList<>(Arrays.asList( "\\.(?i)(CAP|CRZ|SFZ|XRD|CDG|CDU|CHI|CHX|CRD|DFW|FRA|FRF|HND|IA2|IAD|LON|ORD|PAR|PH2|PHX|PRD|SFM|SPZ|SYD|UKB|WAS|WAX|XRD|YHU|YUL)\\.", ":argus\\.")); if (expression == null || expression.isEmpty()) { _logger.error("Expression either null or empty. Cannot retrive DC from the expression. Returning default value PRD."); DC.add("PRD"); } else { List<MetricQuery> queries = getQueries(expression); for(MetricQuery currentQuery: queries) { m = Pattern.compile(patterns.get(0)).matcher(currentQuery.getScope()); while (m.find()) DC.add(m.group().substring(1, m.group().length() - 1).toUpperCase()); m = Pattern.compile(patterns.get(1)).matcher(currentQuery.getScope()); if(m.find()) DC.add("PRD"); } } if (DC.size() == 0) { _logger.info("Unable to identify DC from expression: " + expression +" . Returning default value PRD."); DC.add("PRD"); } return new ArrayList<>(DC); }

Target:
public List<String> getDCFromExpression(String expression) { Set<String> DC = new HashSet<String>(); Matcher m; String dcList = _configuration.getValue(com.salesforce.dva.argus.system.SystemConfiguration.Property.DC_LIST).replaceAll(",","|"); String defaultDC = _configuration.getValue(SystemConfiguration.Property.DC_DEFAULT); ArrayList<String> patterns = new ArrayList<>(Arrays.asList( "\\.(?i)(" + dcList + ")\\.", ":argus\\.")); if (expression == null || expression.isEmpty()) { _logger.error("Expression either null or empty. Cannot retrive DC from the expression. Returning default value " + defaultDC); DC.add(defaultDC); } else { List<MetricQuery> queries = getQueries(expression); for(MetricQuery currentQuery: queries) { m = Pattern.compile(patterns.get(0)).matcher(currentQuery.getScope()); while (m.find()) DC.add(m.group().substring(1, m.group().length() - 1).toUpperCase()); m = Pattern.compile(patterns.get(1)).matcher(currentQuery.getScope()); if(m.find()) DC.add(defaultDC); } } if (DC.size() == 0) { _logger.info("Unable to identify DC from expression: " + expression +" . Returning default value PRD " + defaultDC); DC.add(defaultDC); } return new ArrayList<>(DC); }
Source:
long allocatedSize() { long bloomAllocatedSize = bloomFilter == null ? 0 : bloomFilter.getBitsetSize(); return repetitionLevelColumn.getAllocatedSize() + definitionLevelColumn.getAllocatedSize() + dataColumn.getAllocatedSize() + pageWriter.allocatedSize() + bloomAllocatedSize; }

Target:
long allocatedSize() { return repetitionLevelColumn.getAllocatedSize() + definitionLevelColumn.getAllocatedSize() + dataColumn.getAllocatedSize() + pageWriter.allocatedSize(); }
Source:
public boolean isIntermediateResultComparable() { return true; }

Target:
public boolean isIntermediateResultComparable() { return false; }
Source:
public void testSeek() throws IOException { int bufferSize = 20000; int startPosition = 250000; int length = 5000; final int[] RELATIVE_SEEK_OFFSET = new int[]{-bufferSize*2, -bufferSize, -bufferSize/2, -length, -length/2, 0, length/2, length, bufferSize/2, bufferSize, bufferSize*2}; for (final int seekOffset : RELATIVE_SEEK_OFFSET) { byte[] buffer1 = new byte[length]; SeekableStream unBufferedStream = new SeekableFileStream(BAM_FILE); unBufferedStream.seek(startPosition); int bytesRead = unBufferedStream.read(buffer1, 0, length); Assert.assertEquals(length, bytesRead); byte[] buffer2 = new byte[length]; SeekableStream bufferedStream = new SeekableBufferedStream(new SeekableHTTPStream(new URL(BAM_URL_STRING)), bufferSize); bufferedStream.seek(startPosition); bytesRead = bufferedStream.read(buffer2, 0, length); Assert.assertEquals(length, bytesRead); Assert.assertEquals(buffer1, buffer2); unBufferedStream.seek(startPosition + seekOffset); bytesRead = unBufferedStream.read(buffer1, 0, length); Assert.assertEquals(length, bytesRead); bufferedStream.seek(startPosition + seekOffset); bytesRead = bufferedStream.read(buffer2, 0, length); Assert.assertEquals(length, bytesRead); Assert.assertEquals(buffer1, buffer2, "Error at relative seek offset " + seekOffset); } }

Target:
public void testSeek() throws IOException { final int bufferSize = 20000; final int startPosition = 250000; final int length = 5000; final int[] RELATIVE_SEEK_OFFSET = new int[]{-bufferSize*2, -bufferSize, -bufferSize/2, -length, -length/2, -1, 0, 1, length/2, length, bufferSize/2, bufferSize-1, bufferSize, bufferSize*2}; for (final int seekOffset : RELATIVE_SEEK_OFFSET) { try (SeekableStream unBufferedStream = new SeekableFileStream(BAM_FILE); SeekableBufferedStream bufferedStream = new SeekableBufferedStream(new SeekableHTTPStream(new URL(BAM_URL_STRING)), bufferSize)) { byte[] buffer1 = new byte[length]; unBufferedStream.seek(startPosition); int bytesRead = unBufferedStream.read(buffer1, 0, length); Assert.assertEquals(length, bytesRead); byte[] buffer2 = new byte[length]; bufferedStream.seek(startPosition); bytesRead = bufferedStream.read(buffer2, 0, length); Assert.assertEquals(length, bytesRead); Assert.assertEquals(buffer1, buffer2); unBufferedStream.seek(startPosition + seekOffset); bytesRead = unBufferedStream.read(buffer1, 0, length); Assert.assertEquals(length, bytesRead); Object internalBuffer = bufferedStream.bufferedStream; bufferedStream.seek(startPosition + seekOffset); bytesRead = bufferedStream.read(buffer2, 0, length); Assert.assertEquals(length, bytesRead); Object newInternalBuffer = bufferedStream.bufferedStream; if (seekOffset >=0 && seekOffset < bufferSize) { Assert.assertSame(internalBuffer, newInternalBuffer, "Internal buffer should have been reused for seek offset " + seekOffset); } else { Assert.assertNotSame(internalBuffer, newInternalBuffer, "Internal buffer should not have been reused for seek offset " + seekOffset); } Assert.assertEquals(buffer1, buffer2, "Error at relative seek offset " + seekOffset); } } }
Source:
public List<StartIdentifiedAtlasDbTransactionResponse> startIdentifiedAtlasDbTransactionBatch(int count) { return runTaskTimed("startIdentifiedAtlasDbTransactionBatch", () -> delegate.startIdentifiedAtlasDbTransactionBatch(1)); }

Target:
public List<StartIdentifiedAtlasDbTransactionResponse> startIdentifiedAtlasDbTransactionBatch(int count) { return runTaskTimed("startIdentifiedAtlasDbTransactionBatch", () -> delegate.startIdentifiedAtlasDbTransactionBatch(count)); }
Source:
public void testEmailConstraint() { Validator validator = TestUtil.getValidatorUnderTest(); EmailDummyEntity foo = new EmailDummyEntity( "invalid" ); Set<ConstraintViolation<EmailDummyEntity>> constraintViolations = validator.validate( foo ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Email.class ).withProperty( "email" ) ); }

Target:
public void testEmailConstraint() { Validator validator = TestUtil.getValidatorUnderTest(); EmailDummyEntity foo = new EmailDummyEntity( "test@example.com" ); Set<ConstraintViolation<EmailDummyEntity>> constraintViolations = validator.validate( foo ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Email.class ).withProperty( "email" ) ); }
Source:
protected double getMaxY() { double maxY = super.getMaxY(); if (maxY == 0) { return 10; } if (maxY % 2 == 0) { return maxY; } else { return maxY+1; } }

Target:
protected double getMaxY() { double maxY = super.getMaxY(); if (maxY == 0) { return DEFAULT_MAX_Y; } return maxY + (maxY % 2); }
Source:
public void invalidIfAreaCodeStartsWith0() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(illegalCharacterExceptionMessage); new PhoneNumber("(023) 456-7890"); }

Target:
public void invalidIfAreaCodeStartsWith0() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(illegalAreaOrExchangeCodeMessage); new PhoneNumber("(023) 456-7890"); }
Source:
public void assertSamValid(final File samFile) { final List<String> args = new ArrayList<>(); args.add("I=" + samFile.getAbsolutePath()); ignoreErrors.forEach(s->args.add("IGNORE=" + s )); final int validateExitStatus = runPicardCommandLine(args.toArray(new String[1 + ignoreErrors.size()])); Assert.assertEquals(validateExitStatus, 0, "There were problems in file: " + samFile.getAbsolutePath()); }

Target:
public void assertSamValid(final File samFile) { final List<String> args = new ArrayList<>(); args.add("I=" + samFile.getAbsolutePath()); ignoreErrors.forEach(s -> args.add("IGNORE=" + s)); final int validateExitStatus = runPicardCommandLine(args.toArray(new String[0])); Assert.assertEquals(validateExitStatus, 0, "There were problems in file: " + samFile.getAbsolutePath()); }
Source:
public boolean handle(HttpServletRequest request, HttpServletResponse response, Account account) { System.out.println("----> PostLoginHandler"); return true; }

Target:
public boolean handle(HttpServletRequest request, HttpServletResponse response, Account account) { log.debug("----> PostLoginHandler"); return true; }
Source:
private SshServer setupSSHDaemon() throws Exception { SshServer sshServer = SshServer.setUpDefaultServer(); SimpleGeneratorHostKeyProvider simpleGeneratorHostKeyProvider = new SimpleGeneratorHostKeyProvider(); simpleGeneratorHostKeyProvider.setAlgorithm(KeyUtils.RSA_ALGORITHM); sshServer.setKeyPairProvider(simpleGeneratorHostKeyProvider); sshServer.setPasswordAuthenticator(new PasswordAuthenticator() { @Override public boolean authenticate(String username, String password, ServerSession session) { return username.equals(USER) && password.equals(PASSPHRASE); } }); sshServer.setShellFactory(new ProcessShellFactory(SHELL_ARGS)); sshServer.setCommandFactory(EchoCommandFactory.INSTANCE); return sshServer; }

Target:
private static SshServer setupSSHDaemon() throws Exception { SshServer sshServer = SshServer.setUpDefaultServer(); SimpleGeneratorHostKeyProvider simpleGeneratorHostKeyProvider = new SimpleGeneratorHostKeyProvider(); simpleGeneratorHostKeyProvider.setAlgorithm(KeyUtils.RSA_ALGORITHM); sshServer.setKeyPairProvider(simpleGeneratorHostKeyProvider); sshServer.setPasswordAuthenticator(new PasswordAuthenticator() { @Override public boolean authenticate(String username, String password, ServerSession session) { return USER.equals(username) && PASSPHRASE.equals(password); } }); sshServer.setShellFactory(new ProcessShellFactory(SHELL_ARGS)); sshServer.setCommandFactory(EchoCommandFactory.INSTANCE); return sshServer; }
Source:
public void tookAndTimedOut() { StubMappingScope scope = indexManager.createScope(); SearchQuery<DocumentReference> genericQuery = scope.query() .predicate( f -> f.matchAll() ) .toQuery(); ElasticsearchSearchQuery<DocumentReference> esQuery = genericQuery.extension( ElasticsearchExtension.get() ); ElasticsearchSearchResult<DocumentReference> result = esQuery.fetchAll(); assertNotNull( result.getTook() ); assertNotNull( result.getTimedOut() ); }

Target:
public void tookAndTimedOut() { StubMappingScope scope = indexManager.createScope(); SearchQuery<DocumentReference> genericQuery = scope.query() .predicate( f -> f.matchAll() ) .toQuery(); ElasticsearchSearchQuery<DocumentReference> esQuery = genericQuery.extension( ElasticsearchExtension.get() ); ElasticsearchSearchResult<DocumentReference> result = esQuery.fetchAll(); assertNotNull( result.getTook() ); assertNotNull( result.isTimedOut() ); assertFalse( result.isTimedOut() ); }
Source:
public boolean isClientError(HttpMessage msg) { return isPage404(msg) ? true : HttpStatusCode.isClientError(msg.getResponseHeader().getStatusCode()); }

Target:
public boolean isClientError(HttpMessage msg) { if (isCustomPage(msg, CustomPage.Type.OK_200) || isCustomPage(msg, CustomPage.Type.ERROR_500)) { return false; } if (isCustomPage(msg, CustomPage.Type.NOTFOUND_404) || !parent.getAnalyser().isFileExist(msg)) { return true; } return HttpStatusCode.isClientError(msg.getResponseHeader().getStatusCode()); }
Source:
private org.infinispan.configuration.cache.ConfigurationBuilder createConfigurationBuilder() { org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder.persistence().addStore(JdbcStringBasedStoreConfigurationBuilder.class) .fetchPersistentState(false) .ignoreModifications(false) .purgeOnStartup(false) .shared(false) .table() .dropOnExit(true) .createOnStart(true) .tableNamePrefix("TBL") .idColumnName("ID").idColumnType(DATABASE.getDatabase().getIdColumType()) .dataColumnName("DATA").dataColumnType(DATABASE.getDatabase().getDataColumnType()) .timestampColumnName("TS").timestampColumnType(DATABASE.getDatabase().getTimeStampColumnType()) .segmentColumnName("S").segmentColumnType(DATABASE.getDatabase().getSegmentColumnType()) .dataSource().jndiUrl("jdbc/database"); return builder; }

Target:
private org.infinispan.configuration.cache.ConfigurationBuilder createConfigurationBuilder() { org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder.persistence().addStore(JdbcStringBasedStoreConfigurationBuilder.class) .table() .dropOnExit(true) .tableNamePrefix("TBL") .idColumnName("ID").idColumnType(DATABASE.getDatabase().getIdColumType()) .dataColumnName("DATA").dataColumnType(DATABASE.getDatabase().getDataColumnType()) .timestampColumnName("TS").timestampColumnType(DATABASE.getDatabase().getTimeStampColumnType()) .segmentColumnName("S").segmentColumnType(DATABASE.getDatabase().getSegmentColumnType()) .dataSource().jndiUrl("jdbc/database"); return builder; }
Source:
private boolean matchTraversedDevice(PacketContext pktCtx) { return traversedDevice == null || traversedDeviceInv ^ pktCtx.flowTags().contains( FlowTagger.tagForDevice(traversedDevice)); }

Target:
private boolean matchTraversedDevice(PacketContext pktCtx) { FlowTagger.FlowTag tag = traversedDeviceTag(); return tag == null || traversedDeviceInv ^ pktCtx.flowTags().contains(tag); }
Source:
private void deleteTopic(Datastream datastream) { if (datastream.getMetadata().get(DatastreamMetadataConstants.IS_USER_MANAGED_DESTINATION_KEY).equals("true")) { _log.info("BYOT(bring your own topic), topic will not be deleted"); } else { _transportProviderAdmins.get(datastream.getTransportProviderName()).dropDestination(datastream); } }

Target:
private void deleteTopic(Datastream datastream) { try { if (StringUtils.equals(datastream.getMetadata().get(DatastreamMetadataConstants.IS_USER_MANAGED_DESTINATION_KEY), "true")) { _log.info("BYOT(bring your own topic), topic will not be deleted"); } else { _transportProviderAdmins.get(datastream.getTransportProviderName()).dropDestination(datastream); } } catch (Exception e) { _log.error("Runtime Exception while delete topic", e); } }
Source:
private void aggregate(List<Path> files, Path outputFile) throws GoGoDuckException { CommandLine command = new CommandLine(getGoGoDuckConfig().getNcrcatPath()); command.addArgument("-D2"); command.addArgument("-4"); command.addArgument("-h"); command.addArgument("-O"); if (files.size() == 1) { File file = files.get(0).toFile(); try { if (outputFile.toFile().exists() && outputFile.toFile().isFile()) { logger.info(String.format("Deleting '%s'", outputFile)); Files.delete(outputFile); } logger.info(String.format("Renaming '%s' -> '%s'", file, outputFile)); Files.move(file.toPath(), outputFile); } catch (IOException e) { logger.error(e.getMessage(), e); throw new GoGoDuckException(String.format("Could not rename result file: '%s'", file), e); } } else { logger.info(String.format("Concatenating %d files into '%s'", files.size(), outputFile)); command.addArgument(outputFile.toFile().getAbsolutePath()); Set<String> fileNames = new LinkedHashSet<>(); for (Path file : files) { String filePath = file.toAbsolutePath().toString(); fileNames.add(filePath); } String stdin = StringUtils.join(fileNames, " "); try { execute(command, stdin); } catch (Exception e) { logger.error(String.format("Could not concatenate files: %s into a single file: '%s'", Arrays.toString(fileNames.toArray()), outputFile)); logger.error(e.getMessage(), e); throw new GoGoDuckException(String.format("Could not concatenate %s files into a single file: '%s'", files.size(), outputFile), e); } } }

Target:
private void aggregate(List<Path> files, Path outputFile) throws GoGoDuckException { CommandLine command = new CommandLine(getGoGoDuckConfig().getNcrcatPath()); command.addArgument("-D2"); command.addArgument("-4"); command.addArgument("-h"); command.addArgument("-O"); if (files.size() == 1) { File file = files.get(0).toFile(); try { if (outputFile.toFile().exists() && outputFile.toFile().isFile()) { logger.info(String.format("Deleting '%s'", outputFile)); Files.delete(outputFile); } logger.info(String.format("Renaming '%s' -> '%s'", file, outputFile)); Files.move(file.toPath(), outputFile); } catch (IOException e) { logger.error(e.getMessage(), e); throw new GoGoDuckException(String.format("Could not rename result file: '%s'", file), e); } } else { logger.info(String.format("Concatenating %d files into '%s'", files.size(), outputFile)); command.addArgument(outputFile.toFile().getAbsolutePath()); Set<String> fileNames = new LinkedHashSet<>(); for (Path file : files) { String filePath = file.toAbsolutePath().toString(); fileNames.add(filePath); } String stdin = StringUtils.join(fileNames, " "); try { execute(command, stdin); } catch (Exception e) { throw new GoGoDuckException(String.format("Could not concatenate %s files into a single file: '%s'", files.size(), outputFile), e); } } }
Source:
protected void doWork(IProgressMonitor monitor) throws OseeCoreException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("function", Function.PURGE_BRANCH.name()); BranchState currentState = branch.getBranchState(); BranchArchivedState archivedState = branch.getArchiveState(); ArtifactCache.deCache(branch); branch.setBranchState(BranchState.PURGE_IN_PROGRESS); branch.setArchived(true); OseeEventManager.kickBranchEvent(getClass(), new BranchEvent(BranchEventType.Purging, branch.getGuid())); AcquireResult response = null; try { PurgeBranchRequest requestData = new PurgeBranchRequest(branch.getId(), recursive); response = HttpClientMessage.send(OseeServerContext.BRANCH_CONTEXT, parameters, CoreTranslatorId.PURGE_BRANCH_REQUEST, requestData, null); } catch (OseeCoreException ex) { branch.setBranchState(currentState); branch.setArchived(archivedState.isArchived()); OseeEventManager.kickBranchEvent(getClass(), new BranchEvent(BranchEventType.StateUpdated, branch.getGuid())); throw ex; } if (response.wasSuccessful()) { branch.setStorageState(StorageState.PURGED); branch.setBranchState(BranchState.PURGED); branch.setArchived(true); BranchManager.decache(branch); BranchManager.getCache().reloadCache(); OseeEventManager.kickBranchEvent(getClass(), new BranchEvent(BranchEventType.Purged, branch.getGuid())); } }

Target:
protected void doWork(IProgressMonitor monitor) throws OseeCoreException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("function", Function.PURGE_BRANCH.name()); BranchState currentState = branch.getBranchState(); BranchArchivedState archivedState = branch.getArchiveState(); ArtifactCache.deCache(branch); branch.setBranchState(BranchState.PURGE_IN_PROGRESS); branch.setArchived(true); OseeEventManager.kickBranchEvent(getClass(), new BranchEvent(BranchEventType.Purging, branch.getGuid())); AcquireResult response = null; try { PurgeBranchRequest requestData = new PurgeBranchRequest(branch.getId(), recursive); response = HttpClientMessage.send(OseeServerContext.BRANCH_CONTEXT, parameters, CoreTranslatorId.PURGE_BRANCH_REQUEST, requestData, null); } catch (OseeCoreException ex) { try { branch.setBranchState(currentState); branch.setArchived(archivedState.isArchived()); OseeEventManager.kickBranchEvent(getClass(), new BranchEvent(BranchEventType.StateUpdated, branch.getGuid())); } catch (Exception ex2) { log(ex2); } throw ex; } if (response.wasSuccessful()) { branch.setStorageState(StorageState.PURGED); branch.setBranchState(BranchState.PURGED); branch.setArchived(true); BranchManager.decache(branch); BranchManager.getCache().reloadCache(); OseeEventManager.kickBranchEvent(getClass(), new BranchEvent(BranchEventType.Purged, branch.getGuid())); } }
Source:
private EmbeddedExpirableMetadata( long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit, EntryVersion version) { super(version); this.lifespan = lifespan < 0 ? lifespan : lifespanUnit.toMillis(lifespan); this.maxIdle = maxIdleUnit.toMillis(maxIdle); }

Target:
private EmbeddedExpirableMetadata( long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit, EntryVersion version) { super(version); this.lifespan = lifespan < 0 ? -1 : lifespanUnit.toMillis(lifespan); this.maxIdle = maxIdle < 0 ? -1 : maxIdleUnit.toMillis(maxIdle); }
Source:
public void shouldAddSystemPermissionsOnPostUserPersistedEvent() throws Exception { Injector injector = Guice.createInjector(new BaseModule()); UserManager userManager = injector.getInstance(UserManager.class); when(userManager.getByName(eq(NAME))).thenReturn(user); AdminPermissionInitializer creator = injector.getInstance(AdminPermissionInitializer.class); creator.onEvent( new PostUserPersistedEvent(new UserImpl(NAME, EMAIL, NAME, PASSWORD, emptyList()))); verify(permissionsManager) .storePermission( argThat( new ArgumentMatcher<SystemPermissionsImpl>() { @Override public boolean matches(Object argument) { return ((SystemPermissionsImpl) argument).getUserId().equals(NAME); } })); }

Target:
public void shouldAddSystemPermissionsOnPostUserPersistedEvent() throws Exception { when(userManager.getByName(eq(NAME))).thenReturn(user); initializer.init(); initializer.onEvent( new PostUserPersistedEvent(new UserImpl(NAME, EMAIL, NAME, PASSWORD, emptyList()))); verify(permissionsManager) .storePermission( argThat( new ArgumentMatcher<SystemPermissionsImpl>() { @Override public boolean matches(Object argument) { return ((SystemPermissionsImpl) argument).getUserId().equals(NAME); } })); }