auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void suggestChangeReviewer(final Change.Id change, final String query, final int limit, final AsyncCallback<List<ReviewerInfo>> callback) { run(callback, new Action<List<ReviewerInfo>>() { public List<ReviewerInfo> run(final ReviewDb db) throws OrmException { final ChangeControl changeControl; try { changeControl = changeControlFactory.controlFor(change); } catch (NoSuchChangeException e) { return Collections.emptyList(); } VisibilityControl visibilityControl = new VisibilityControl() { @Override public boolean isVisible(Account account) throws OrmException { IdentifiedUser who = identifiedUserFactory.create(reviewDbProvider, account.getId()); return changeControl.getChange().getStatus() == Change.Status.DRAFT || changeControl.forUser(who).isVisible(reviewDbProvider.get()); } }; final List<AccountInfo> suggestedAccounts = suggestAccount(db, query, Boolean.TRUE, limit, visibilityControl); final List<ReviewerInfo> reviewer = new ArrayList<ReviewerInfo>(suggestedAccounts.size()); for (final AccountInfo a : suggestedAccounts) { reviewer.add(new ReviewerInfo(a)); } final List<GroupReference> suggestedAccountGroups = suggestAccountGroup(db, query, limit); for (final GroupReference g : suggestedAccountGroups) { if (suggestGroupAsReviewer(changeControl.getProject().getNameKey(), g)) { reviewer.add(new ReviewerInfo(g)); } } Collections.sort(reviewer); if (reviewer.size() <= limit) { return reviewer; } else { return reviewer.subList(0, limit); } } }); }

Target:
public void suggestChangeReviewer(final Change.Id change, final String query, final int limit, final AsyncCallback<List<ReviewerInfo>> callback) { run(callback, new Action<List<ReviewerInfo>>() { public List<ReviewerInfo> run(final ReviewDb db) throws OrmException { final ChangeControl changeControl; try { changeControl = changeControlFactory.controlFor(change); } catch (NoSuchChangeException e) { return Collections.emptyList(); } VisibilityControl visibilityControl = new VisibilityControl() { @Override public boolean isVisible(Account account) throws OrmException { IdentifiedUser who = identifiedUserFactory.create(reviewDbProvider, account.getId()); return changeControl.forUser(who).isRefVisible(); } }; final List<AccountInfo> suggestedAccounts = suggestAccount(db, query, Boolean.TRUE, limit, visibilityControl); final List<ReviewerInfo> reviewer = new ArrayList<ReviewerInfo>(suggestedAccounts.size()); for (final AccountInfo a : suggestedAccounts) { reviewer.add(new ReviewerInfo(a)); } final List<GroupReference> suggestedAccountGroups = suggestAccountGroup(db, query, limit); for (final GroupReference g : suggestedAccountGroups) { if (suggestGroupAsReviewer(changeControl.getProject().getNameKey(), g)) { reviewer.add(new ReviewerInfo(g)); } } Collections.sort(reviewer); if (reviewer.size() <= limit) { return reviewer; } else { return reviewer.subList(0, limit); } } }); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("UndeleteRequest["); sb.append("BlobID=").append(blobId); sb.append(", ").append("PartitionId=").append(blobId.getPartition()); sb.append(", ").append("ClientId=").append(clientId); sb.append(", ").append("CorrelationId=").append(correlationId); sb.append(", ").append("AccountId=").append(blobId.getAccountId()); sb.append(", ").append("ContainerId=").append(blobId.getContainerId()); sb.append("]"); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("UndeleteRequest["); sb.append("BlobID=").append(blobId); sb.append(", ").append("PartitionId=").append(blobId.getPartition()); sb.append(", ").append("ClientId=").append(clientId); sb.append(", ").append("CorrelationId=").append(correlationId); sb.append(", ").append("AccountId=").append(blobId.getAccountId()); sb.append(", ").append("ContainerId=").append(blobId.getContainerId()); sb.append(", ").append("OperationTimeMs=").append(operationTimeMs); sb.append("]"); return sb.toString(); }
Source:
public void registerTransformers(SubsystemTransformerRegistration subsystem) { ResourceTransformationDescriptionBuilder builder = TransformationDescriptionBuilder.Factory.createSubsystemInstance(); builder.getAttributeBuilder().setDiscard(new DiscardAttributeChecker.DefaultDiscardAttributeChecker() { @Override protected boolean isValueDiscardable(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) { return attributeValue.isDefined() && attributeValue.equals(XTSSubsystemDefinition.HOST_NAME.getDefaultValue()); } }, XTSSubsystemDefinition.HOST_NAME) .setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(new ModelNode(false)), XTSSubsystemDefinition.DEFAULT_CONTEXT_PROPAGATION, XTSSubsystemDefinition.ASYNC_REGISTRATION) .addRejectCheck(RejectAttributeChecker.DEFINED, XTSSubsystemDefinition.HOST_NAME, XTSSubsystemDefinition.DEFAULT_CONTEXT_PROPAGATION, XTSSubsystemDefinition.ASYNC_REGISTRATION) .end(); TransformationDescription.Tools.register(builder.build(), subsystem, ModelVersion.create(1, 1, 0)); }

Target:
public void registerTransformers(SubsystemTransformerRegistration subsystem) { ChainedTransformationDescriptionBuilder chainedBuilder = TransformationDescriptionBuilder.Factory.createChainedSubystemInstance(XTSExtension.CURRENT_MODEL_VERSION); ResourceTransformationDescriptionBuilder builderEap72 = chainedBuilder.createBuilder(XTSExtension.CURRENT_MODEL_VERSION, MODEL_VERSION_EAP71); builderEap72.getAttributeBuilder() .addRejectCheck(RejectAttributeChecker.DEFINED, XTSSubsystemDefinition.ASYNC_REGISTRATION) .setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(new ModelNode(false)), XTSSubsystemDefinition.ASYNC_REGISTRATION) .end(); ResourceTransformationDescriptionBuilder builderEap70 = chainedBuilder.createBuilder(MODEL_VERSION_EAP71, MODEL_VERSION_EAP64); builderEap70.getAttributeBuilder() .addRejectCheck(RejectAttributeChecker.DEFINED, XTSSubsystemDefinition.HOST_NAME, XTSSubsystemDefinition.DEFAULT_CONTEXT_PROPAGATION) .setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(new ModelNode(false)), XTSSubsystemDefinition.DEFAULT_CONTEXT_PROPAGATION) .setDiscard(new DiscardAttributeChecker.DefaultDiscardAttributeChecker() { @Override protected boolean isValueDiscardable(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) { return attributeValue.isDefined() && attributeValue.equals(XTSSubsystemDefinition.HOST_NAME.getDefaultValue()); } }, XTSSubsystemDefinition.HOST_NAME) .end(); chainedBuilder.buildAndRegister(subsystem, new ModelVersion[]{ MODEL_VERSION_EAP64, MODEL_VERSION_EAP71, }); }
Source:
protected boolean isUnicityCheckEnabled() { return Framework.getRuntime().getService(FileManager.class).isUnicityEnabled(); }

Target:
protected boolean isUnicityCheckEnabled() { return Framework.getService(FileManager.class).isUnicityEnabled(); }
Source:
public void start() { JobModel jobModel = null; try { jobModel = getJobModel(); CheckpointManager checkpointManager = new TaskConfigJava(jobModel.getConfig()).getCheckpointManager(null); if (checkpointManager != null) { checkpointManager.createStream(); } } catch (Exception e) { LOGGER.error("Exception while trying to getJobModel.", e); if (coordinatorListener != null) { coordinatorListener.onCoordinatorFailure(e); } } if (jobModel != null && jobModel.getContainers().containsKey(processorId)) { if (coordinatorListener != null) { coordinatorListener.onNewJobModel(processorId, jobModel); } } else { stop(); } }

Target:
public void start() { JobModel jobModel = null; try { jobModel = getJobModel(); CheckpointManager checkpointManager = new TaskConfigJava(jobModel.getConfig()).getCheckpointManager(null); if (checkpointManager != null) { checkpointManager.createResources(); } } catch (Exception e) { LOGGER.error("Exception while trying to getJobModel.", e); if (coordinatorListener != null) { coordinatorListener.onCoordinatorFailure(e); } } if (jobModel != null && jobModel.getContainers().containsKey(processorId)) { if (coordinatorListener != null) { coordinatorListener.onNewJobModel(processorId, jobModel); } } else { stop(); } }
Source:
private void refreshTagsFromFile(final Path path) { try (final Stream<String> lines = Files.lines(path)) { lines.forEach(label -> { final String[] labelParts = label.split("=", 2); tags.put(labelParts[0], labelParts[1]); }); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
private void refreshTagsFromFile(final Path path) { try (final Stream<String> lines = Files.lines(path)) { lines.forEach(label -> { final String[] labelParts = label.split("=", 2); if (tags.get(labelParts[0]) != null) { tags.put(labelParts[0], labelParts[1].replace("\"", "")); } }); } catch (IOException e) { } }
Source:
public void testWordCount() throws Exception { int wordCount = 2732; String myFile = createFile(wordCount); BulkCommand command = new BulkCommand.Builder(WordCountAction.ACTION_NAME, myFile, "system").useGenericScrollerType().build(); String commandId = bulkService.submit(command); BulkStatus status = bulkService.getStatus(commandId); assertTrue(bulkService.await(commandId, Duration.ofSeconds(20))); status = bulkService.getStatus(commandId); assertEquals(COMPLETED, status.getState()); assertEquals(wordCount, status.getResult().get("wordCount")); System.out.println(status); }

Target:
public void testWordCount() throws Exception { int wordCount = 2732; String myFile = createFile(wordCount); BulkCommand command = new BulkCommand.Builder(WordCountAction.ACTION_NAME, myFile, "system").useGenericScroller().build(); String commandId = bulkService.submit(command); assertTrue(bulkService.await(commandId, Duration.ofSeconds(20))); BulkStatus status = bulkService.getStatus(commandId); assertEquals(COMPLETED, status.getState()); assertEquals(wordCount, status.getResult().get("wordCount")); }
Source:
public int delete(ComplexEventChunk<StateEvent> deletingEventChunk, Object storeEvents) { int numberOfEventsBeforeDelete = ((IndexedEventHolder) storeEvents).getAllEvents().size(); deletingEventChunk.reset(); while (deletingEventChunk.hasNext()) { StateEvent deletingEvent = deletingEventChunk.next(); collectionExecutor.delete(deletingEvent, (IndexedEventHolder) storeEvents); } return numberOfEventsBeforeDelete - ((IndexedEventHolder) storeEvents).getAllEvents().size(); }

Target:
public void delete(ComplexEventChunk<StateEvent> deletingEventChunk, Object storeEvents) { deletingEventChunk.reset(); while (deletingEventChunk.hasNext()) { StateEvent deletingEvent = deletingEventChunk.next(); collectionExecutor.delete(deletingEvent, (IndexedEventHolder) storeEvents); } }
Source:
private Boolean checkSchemaVersion() { String sqlStatement = "SELECT a.value creationMajorVersion, b.value creationMinorVersion FROM tsk_db_info_extended a, tsk_db_info_extended b " + " WHERE a.name = 'CREATION_SCHEMA_MAJOR_VERSION' and b.name = 'CREATION_SCHEMA_MINOR_VERSION';"; try (CaseDbQuery query = Case.getCurrentCaseThrows().getSleuthkitCase().executeQuery(sqlStatement);) { ResultSet schemaVersion = query.getResultSet(); while (schemaVersion.next()) { int creationMajorVersion = schemaVersion.getInt("creationMajorVersion"); int creationMinorVersion = schemaVersion.getInt("creationMinorVersion"); if ((creationMajorVersion == 8 && creationMinorVersion >= 3) || creationMajorVersion > 8) { schemaVersion.close(); return true; } } schemaVersion.close(); } catch (SQLException | TskCoreException | NoCurrentCaseException ex) { logger.log(Level.SEVERE, "Failed to get the Create Major and Minor Schema Versions", ex); } return false; }

Target:
private Boolean checkSchemaVersion() { try { CaseDbSchemaVersionNumber creationVersion = Case.getCurrentCaseThrows().getSleuthkitCase().getDBSchemaCreationVersion(); if ((creationVersion.getMajor() == 8 && creationVersion.getMinor() >= 3) || creationVersion.getMajor() > 8) { return true; } } catch (NoCurrentCaseException ex) { logger.log(Level.WARNING, "Failed to get creation schema version: ", ex); } return false; }
Source:
public String expand(Map<String, ?> variables) { String expanded = super.expand(variables); if (this.json) { expanded = expanded.substring( expanded.indexOf(JSON_TOKEN_START_ENCODED) + JSON_TOKEN_START_ENCODED.length()); expanded = JSON_TOKEN_START + expanded; expanded = expanded.substring(0, expanded.lastIndexOf(JSON_TOKEN_END_ENCODED)); expanded += JSON_TOKEN_END; } return expanded; }

Target:
public String expand(Map<String, ?> variables) { String expanded = super.expand(variables); if (this.json) { StringBuilder sb = new StringBuilder(); sb.append(JSON_TOKEN_START); sb.append(expanded, expanded.indexOf(JSON_TOKEN_START_ENCODED) + JSON_TOKEN_START_ENCODED.length(), expanded.lastIndexOf(JSON_TOKEN_END_ENCODED)); sb.append(JSON_TOKEN_END); return sb.toString(); } return expanded; }
Source:
public static Set<Class<?>> getFromJARFile(final ClassLoader loader, final String jar, final String packageName, final boolean ignoreSubPackages) throws IOException, ClassNotFoundException { final Set<Class<?>> classes = new HashSet<Class<?>>(); final JarInputStream jarFile = new JarInputStream(new FileInputStream(jar)); try { JarEntry jarEntry; do { jarEntry = jarFile.getNextJarEntry(); if (jarEntry != null) { String className = jarEntry.getName(); if (className.endsWith(".class")) { String classPackageName = getPackageName(className); if ((ignoreSubPackages && classPackageName.equals(packageName)) || (!ignoreSubPackages && isSubPackage( classPackageName, packageName))) { className = stripFilenameExtension(className); classes.add(Class.forName(className.replace('/', '.'), true, loader)); } } } } while (jarEntry != null); } finally { jarFile.close(); } return classes; }

Target:
public static Set<Class<?>> getFromJARFile(final ClassLoader loader, final String jar, final String packageName, final boolean ignoreSubPackages) throws IOException, ClassNotFoundException { final Set<Class<?>> classes = new HashSet<Class<?>>(); final JarInputStream jarFile = new JarInputStream(new FileInputStream(jar)); try { JarEntry jarEntry; do { jarEntry = jarFile.getNextJarEntry(); if (jarEntry != null) { String className = jarEntry.getName(); if (className.endsWith(".class")) { String classPackageName = getPackageName(className); if (classPackageName.equals(packageName) || (!ignoreSubPackages && isSubPackage(classPackageName, packageName))) { className = stripFilenameExtension(className); classes.add(Class.forName(className.replace('/', '.'), true, loader)); } } } } while (jarEntry != null); } finally { jarFile.close(); } return classes; }
Source:
public MavenProject buildProjectFromArtifact(Artifact artifact) throws MojoExecutionException { MavenProject mavenProject; Artifact projectArtifact = repositorySystem.createProjectArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); try { mavenProject = projectBuilder.build(projectArtifact, projectBuildingRequest).getProject(); } catch (ProjectBuildingException e) { log .warn(format("The artifact [%s] seems to have some warnings, enable logs for more information", artifact.toString())); if (log.isDebugEnabled()) { log.warn(format("The artifact [%s] had the following issue ", artifact.toString()), e); } if (e.getResults() == null || e.getResults().size() != 1) { throw new MojoExecutionException( format("There was an issue while trying to create a maven project from the artifact [%s]", artifact.toString()), e); } final ProjectBuildingResult projectBuildingResult = e.getResults().get(0); final List<ModelProblem> collect = projectBuildingResult.getProblems().stream() .filter(modelProblem -> modelProblem.getSeverity().equals(ModelProblem.Severity.FATAL)).collect( Collectors.toList()); if (!collect.isEmpty()) { throw new MojoExecutionException(format( "There was an issue while trying to create a maven project from the artifact [%s], several FATAL errors were found", artifact.toString()), e); } mavenProject = projectBuildingResult.getProject(); } return mavenProject; }

Target:
public MavenProject buildProjectFromArtifact(Artifact artifact) throws MojoExecutionException { MavenProject mavenProject; Artifact projectArtifact = repositorySystem.createProjectArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); try { mavenProject = projectBuilder.build(projectArtifact, projectBuildingRequest).getProject(); } catch (ProjectBuildingException e) { if (log.isDebugEnabled()) { log.warn(format("The artifact [%s] had the following issue ", artifact.toString()), e); } if (e.getResults() == null || e.getResults().size() != 1) { throw new MojoExecutionException( format("There was an issue while trying to create a maven project from the artifact [%s]", artifact.toString()), e); } final ProjectBuildingResult projectBuildingResult = e.getResults().get(0); final List<ModelProblem> collect = projectBuildingResult.getProblems().stream() .filter(modelProblem -> modelProblem.getSeverity().equals(ModelProblem.Severity.FATAL)).collect( Collectors.toList()); if (!collect.isEmpty()) { throw new MojoExecutionException(format( "There was an issue while trying to create a maven project from the artifact [%s], several FATAL errors were found", artifact.toString()), e); } mavenProject = projectBuildingResult.getProject(); } return mavenProject; }
Source:
public ByteBufferInputStream getStream() { if (stream != null) { return stream; } if (byteBuf == null) { return null; } ByteBuffer temp = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.writeBytes(temp); byteBuf.release(); byteBuf = null; stream = new ByteBufferInputStream(temp); return stream; }

Target:
public ByteBufferInputStream getStream() { if (stream != null) { return stream; } if (byteBuf == null) { return null; } ByteBuffer temp = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.readBytes(temp); byteBuf.release(); byteBuf = null; temp.flip(); stream = new ByteBufferInputStream(temp); return stream; }
Source:
private void showContributions(@NonNull List<Contribution> contributions) { view.showProgress(false); if (contributions.size() == 0) { view.showWelcomeTip(true); view.showNoContributionsUI(true); } else { view.showWelcomeTip(false); view.showNoContributionsUI(false); view.setUploadCount(contributions.size()); view.showContributions(contributions); this.contributionList.clear(); this.contributionList.addAll(contributions); } }

Target:
private void showContributions(@NonNull List<Contribution> contributions) { view.showProgress(false); if (contributions.isEmpty()) { view.showWelcomeTip(true); view.showNoContributionsUI(true); } else { view.showWelcomeTip(false); view.showNoContributionsUI(false); view.setUploadCount(contributions.size()); view.showContributions(contributions); this.contributionList.clear(); this.contributionList.addAll(contributions); } }
Source:
private void verifyConfigs(StoreConfig storeConfig, DiskManagerConfig diskManagerConfig) throws StoreException { if (storeConfig.storeDeletedMessageRetentionHours < TimeUnit.SECONDS.toHours(storeConfig.storeDataFlushIntervalSeconds) + 1) { throw new StoreException("Message retention days must be greater than the store flush interval period", StoreErrorCodes.Initialization_Error); } if (diskManagerConfig.diskManagerReserveFileDirName.length() == 0) { throw new StoreException("Reserve file directory name is empty", StoreErrorCodes.Initialization_Error); } }

Target:
private void verifyConfigs(StoreConfig storeConfig, DiskManagerConfig diskManagerConfig) throws StoreException { if (storeConfig.storeDeletedMessageRetentionHours < TimeUnit.SECONDS.toHours(storeConfig.storeDataFlushIntervalSeconds) + 1) { throw new StoreException("Message retention hours must be greater than the store flush interval period", StoreErrorCodes.Initialization_Error); } if (diskManagerConfig.diskManagerReserveFileDirName.length() == 0) { throw new StoreException("Reserve file directory name is empty", StoreErrorCodes.Initialization_Error); } }
Source:
public String nextValue() { int val = _gen.nextValue().intValue(); _laststring = _values.get(val); return _laststring; }

Target:
public String nextValue() { laststring = values.get(gen.nextValue()); return laststring; }
Source:
public static List<ChangeMessage> sortChangeMessages( Iterable<ChangeMessage> changeMessage) { return ChangeNotes.MESSAGE_BY_TIME.sortedCopy(changeMessage); }

Target:
private static List<ChangeMessage> sortChangeMessages( Iterable<ChangeMessage> changeMessage) { return ChangeNotes.MESSAGE_BY_TIME.sortedCopy(changeMessage); }
Source:
public void logMessage(int code, String message, Throwable t) { new PluginLog(this).logMessage(code, message, t); }

Target:
public void logMessage(int code, String message, Throwable t) { getPluginLog().logMessage(code, message, t); }
Source:
public static void setup() { gitDaemonEnabled = System.getProperty("org.uberfire.nio.git.daemon.enabled"); gitSshEnabled = System.getProperty("org.uberfire.nio.git.ssh.enabled"); System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); }

Target:
public static void setup() { System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); }
Source:
private void sanitizeIrrelevantComponents(AnalysisJobBuilder ajb, TransformerComponentBuilder<?> tjb) { final List<AnalysisJobBuilder> relevantAnalysisJobBuilders = createRelevantAnalysisJobBuildersList(ajb); for (AnalysisJobBuilder relevantAnalysisJobBuilder : relevantAnalysisJobBuilders) { final Collection<ComponentBuilder> componentBuilders = relevantAnalysisJobBuilder.getComponentBuilders(); for (ComponentBuilder componentBuilder : componentBuilders) { boolean importantComponent = componentBuilder == tjb; final List<OutputDataStream> streams = componentBuilder.getOutputDataStreams(); for (OutputDataStream stream : streams) { if (componentBuilder.isOutputDataStreamConsumed(stream)) { final AnalysisJobBuilder childJobBuilder = componentBuilder.getOutputDataStreamJobBuilder( stream); if (relevantAnalysisJobBuilders.contains(childJobBuilder)) { importantComponent = true; } else { childJobBuilder.removeAllComponents(); } } } if (!importantComponent && componentBuilder instanceof AnalyzerComponentBuilder) { relevantAnalysisJobBuilder.removeComponent(componentBuilder); } if (!importantComponent) { if (componentBuilder.getInput().length == 0) { relevantAnalysisJobBuilder.removeComponent(componentBuilder); } } } } }

Target:
private void sanitizeIrrelevantComponents(AnalysisJobBuilder ajb, TransformerComponentBuilder<?> tjb) { final List<AnalysisJobBuilder> relevantAnalysisJobBuilders = createRelevantAnalysisJobBuildersList(ajb); for (AnalysisJobBuilder relevantAnalysisJobBuilder : relevantAnalysisJobBuilders) { final Collection<ComponentBuilder> componentBuilders = relevantAnalysisJobBuilder.getComponentBuilders(); for (ComponentBuilder componentBuilder : componentBuilders) { boolean importantComponent = componentBuilder == tjb; final List<OutputDataStream> streams = componentBuilder.getOutputDataStreams(); for (OutputDataStream stream : streams) { if (componentBuilder.isOutputDataStreamConsumed(stream)) { final AnalysisJobBuilder childJobBuilder = componentBuilder.getOutputDataStreamJobBuilder( stream); if (relevantAnalysisJobBuilders.contains(childJobBuilder)) { importantComponent = true; } else { childJobBuilder.removeAllComponents(); } } } if (!importantComponent && componentBuilder instanceof AnalyzerComponentBuilder) { relevantAnalysisJobBuilder.removeComponent(componentBuilder); } if (!importantComponent) { if (!componentBuilder.isConfigured(false)) { relevantAnalysisJobBuilder.removeComponent(componentBuilder); } } } } }
Source:
private void createTable(Admin admin, TableName tableName) throws IOException { HColumnDescriptor hcd = new HColumnDescriptor(COLUMN_FAMILY).setMaxVersions(MAX_VERSIONS); HColumnDescriptor family2 = new HColumnDescriptor(COLUMN_FAMILY2).setMaxVersions(MAX_VERSIONS); admin.createTable( new HTableDescriptor(tableName) .addFamily(hcd) .addFamily(family2)); }

Target:
private void createTable(Admin admin, TableName tableName) throws IOException { Assert.assertFalse("Table should not exist", admin.tableExists(tableName)); HColumnDescriptor hcd = new HColumnDescriptor(COLUMN_FAMILY).setMaxVersions(MAX_VERSIONS); admin.createTable(new HTableDescriptor(tableName).addFamily(hcd)); Assert.assertTrue("Table does not exist", admin.tableExists(tableName)); }
Source:
private String nestedResultMapId(Result result) { String resultMapId = result.one().resultMapId(); if (resultMapId.length() < 1) { resultMapId = result.many().resultMapId(); } if (!resultMapId.contains(".")) { resultMapId = type.getName() + "." + resultMapId; } return resultMapId; }

Target:
private String nestedResultMapId(Result result) { String resultMapId = result.one().resultMap(); if (resultMapId.length() < 1) { resultMapId = result.many().resultMap(); } if (!resultMapId.contains(".")) { resultMapId = type.getName() + "." + resultMapId; } return resultMapId; }
Source:
public MapLookupExtractor( @JsonProperty("map") Map<String, String> map, @JsonProperty("isOneToOne") boolean isOneToOne ) { this.isOneToOne = isOneToOne; this.map = Preconditions.checkNotNull(this.isOneToOne ? HashBiMap.create(map) : map, "map"); }

Target:
public MapLookupExtractor( @JsonProperty("map") Map<String, String> map, @JsonProperty("isOneToOne") boolean isOneToOne ) { Preconditions.checkNotNull(map, "map"); this.isOneToOne = isOneToOne; if (this.isOneToOne) { this.map = HashBiMap.create(map); this.reverseMap = ((HashBiMap<String, String>) this.map).inverse(); } else { this.map = map; this.reverseMap = null; } }
Source:
public ValidationResult defaultRouteNetworkCannotBeExternal(Network network) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_DEFAULT_ROUTE_NETWORK_CANNOT_BE_EXTERNAL, String.format(NETWORK_NAME_REPLACEMENT, network.getName())).when( networkCluster.isManagement() && network.isExternal()); }

Target:
public ValidationResult defaultRouteNetworkCannotBeExternal(Network network) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_DEFAULT_ROUTE_NETWORK_CANNOT_BE_EXTERNAL, String.format(NETWORK_NAME_REPLACEMENT, network.getName())).when( networkCluster.isDefaultRoute() && network.isExternal()); }
Source:
public Collection<Diagram> evaluate(EObject source, IParameterValueList2 parameterValues, IFacetManager facetManager) throws DerivedTypedElementException { List<Diagram> result = new ArrayList<Diagram>(); Collection<Setting> settings = EMFHelper.getUsages(source); if (settings != null) { for (Setting setting : settings) { Diagram diagram = NotationUtils.getDiagramFromRef(setting.getEObject(), source); if (diagram != null) { result.add(diagram); } } } return result; }

Target:
public Collection<Diagram> evaluate(EObject source, IParameterValueList2 parameterValues, IFacetManager facetManager) throws DerivedTypedElementException { List<Diagram> result = new ArrayList<Diagram>(); Collection<Setting> settings = EMFHelper.getUsages(source); if (settings != null) { for (Setting setting : settings) { Diagram diagram = NotationUtils.getOwnedDiagram(setting.getEObject(), source); if (diagram != null) { result.add(diagram); } } } return result; }
Source:
private static List<License> getLicenses() { LicenseService.Iface licenseClient = new ThriftClients().makeLicenseClient(); try { return licenseClient.getLicenses(); } catch (TException e) { LOGGER.error("Could not get license: " + e.getMessage(), e); return null; } }

Target:
private static List<License> getLicenses() throws TException { LicenseService.Iface licenseClient = new ThriftClients().makeLicenseClient(); return licenseClient.getLicenses(); }
Source:
public void testClosingAlreadyClosedJob() { try { TSalesforceInputProperties properties = createTSalesforceInputProperties(false, true); properties.manualQuery.setValue(false); SalesforceBulkQueryInputReader reader = (SalesforceBulkQueryInputReader) this.<IndexedRecord>createBoundedReader(properties); boolean hasRecord = reader.start(); List<IndexedRecord> rows = new ArrayList<>(); while (hasRecord) { IndexedRecord unenforced = reader.getCurrent(); rows.add(unenforced); hasRecord = reader.advance(); } reader.close(); reader.close(); } catch(Throwable t) { Assert.fail("This test shouldn't throw any errors, since we're closing already closed job"); } }

Target:
public void testClosingAlreadyClosedJob() { try { TSalesforceInputProperties properties = createTSalesforceInputProperties(false, true); properties.manualQuery.setValue(false); SalesforceBulkQueryInputReader reader = (SalesforceBulkQueryInputReader) this.<IndexedRecord>createBoundedReader(properties); reader.start(); reader.close(); reader.close(); } catch(Throwable t) { Assert.fail("This test shouldn't throw any errors, since we're closing already closed job"); } }
Source:
protected void doAfterSelectionChange(final int uiRowIndex, final int uiColumnIndex) { if (getModel().getSelectedCells().stream().map(GridData.SelectedCell::getRowIndex).distinct().count() > 1) { super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); return; } if (getModel().getSelectedHeaderCells().size() > 0) { super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); return; } if (uiRowIndex < model.getRowCount() - 1) { if (expression.isPresent()) { final Context context = expression.get(); fireDomainObjectSelectionEvent(context.getContextEntry().get(uiRowIndex).getVariable()); return; } } super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); }

Target:
protected void doAfterSelectionChange(final int uiRowIndex, final int uiColumnIndex) { if (hasAnyHeaderCellSelected() || hasMultipleRowsSelected()) { super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); return; } if (uiRowIndex < model.getRowCount() - 1) { if (expression.isPresent()) { final Context context = expression.get(); fireDomainObjectSelectionEvent(context.getContextEntry().get(uiRowIndex).getVariable()); return; } } super.doAfterSelectionChange(uiRowIndex, uiColumnIndex); }
Source:
public void testMergeTuplesSorted() throws DbException { TupleBatchBuffer[] randomTuples = new TupleBatchBuffer[3]; randomTuples[0] = generateRandomTuples(123, true); randomTuples[1] = generateRandomTuples(42, true); randomTuples[2] = generateRandomTuples(99, true); TupleSource[] children = new TupleSource[3]; children[0] = new TupleSource(randomTuples[0]); children[1] = new TupleSource(randomTuples[1]); children[2] = new TupleSource(randomTuples[2]); NAryOperator merge = new Merge(children, new int[] { 0 }, new boolean[] { true }); merge.open(null); TupleBatch tb; ArrayList<Long> idCollector = new ArrayList<Long>(); while (!merge.eos()) { tb = merge.nextReady(); if (tb != null) { for (int i = 0; i < tb.numTuples(); i++) { idCollector.add(tb.getLong(0, i)); } } } merge.close(); Long previous = null; for (Long index : idCollector) { if (previous != null) { assertEquals(true, previous <= index); } previous = index; } }

Target:
public void testMergeTuplesSorted() throws DbException { TupleBatchBuffer[] randomTuples = new TupleBatchBuffer[3]; randomTuples[0] = generateRandomTuples(52300, true); randomTuples[1] = generateRandomTuples(14200, true); randomTuples[2] = generateRandomTuples(29900, true); TupleSource[] children = new TupleSource[3]; children[0] = new TupleSource(randomTuples[0]); children[1] = new TupleSource(randomTuples[1]); children[2] = new TupleSource(randomTuples[2]); NAryOperator merge = new Merge(children, new int[] { 0, 1 }, new boolean[] { true, true }); merge.open(null); TupleBatch tb; final ArrayList<Entry<Long, String>> entries = new ArrayList<Entry<Long, String>>(); while (!merge.eos()) { tb = merge.nextReady(); if (tb != null) { for (int i = 0; i < tb.numTuples(); i++) { entries.add(new SimpleEntry<Long, String>(tb.getLong(0, i), tb.getString(1, i))); } } } merge.close(); assertEquals(52300 + 14200 + 29900, entries.size()); Comparator<Entry<Long, String>> comparator = new EntryComparator(); Entry<Long, String> previous = null; for (Entry<Long, String> entry : entries) { if (previous != null) { assertTrue(comparator.compare(previous, entry) <= 0); } previous = entry; } }
Source:
public void testTransformWithoutIdParam() throws IOException, CatalogTransformerException { Metacard metacard = transformer.transform(new ByteArrayInputStream(sampleBasicMetacard().getBytes())); assertThat("ddf.metacard", is(metacard.getMetacardType().getName())); assertThat("myId", is(metacard.getId())); }

Target:
public void testTransformWithoutIdParam() throws IOException, CatalogTransformerException { Metacard metacard = transformer.transform(new ByteArrayInputStream(sampleJsonExtensibleA().getBytes())); assertThat(metacard.getMetacardType().getName(), is("MetacardTypeA")); assertThat(metacard.getId(), is(DEFAULT_ID)); }
Source:
public void theDeviceDebugInformationShouldBeEnabled() throws Throwable { final DlmsDevice device = dlmsDeviceRepository.findByDeviceIdentification(PROPERTIES_MAP.put( Keys.KEY_DEVICE_IDENTIFICATION, ScenarioContext.Current().get(Keys.KEY_DEVICE_IDENTIFICATION) .toString())); assertTrue("Debug mode", device.isInDebugMode()); }

Target:
public void theDeviceDebugInformationShouldBeEnabled() throws Throwable { final DlmsDevice device = dlmsDeviceRepository.findByDeviceIdentification(ScenarioContext.Current() .get(Keys.KEY_DEVICE_IDENTIFICATION).toString()); assertTrue("Debug mode", device.isInDebugMode()); }
Source:
public PortfolioItemSummary summarize() { StringBuilder buf = new StringBuilder(96); IborCapFloorLeg mainLeg = product.getCapFloorLeg(); buf.append(SummarizerUtils.datePeriod(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); buf.append(' '); buf.append(SummarizerUtils.amount(mainLeg.getCurrency(), mainLeg.getNotional().getInitialValue())); buf.append(' '); if (mainLeg.getPayReceive().isReceive()) { buf.append("Rec "); summarizeMainLeg(mainLeg, buf); buf.append(getPremium().isPresent() ? " / Pay Premium" : (product.getPayLeg().isPresent() ? " / Pay Periodic" : "")); } else { buf.append("Rec "); buf.append(getPremium().isPresent() ? "Premium" : (product.getPayLeg().isPresent() ? "Periodic" : "")); buf.append(" / Pay "); summarizeMainLeg(mainLeg, buf); } buf.append(" : "); buf.append(SummarizerUtils.dateRange(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); return SummarizerUtils.summary(this, ProductType.IBOR_CAP_FLOOR, buf.toString(), mainLeg.getCurrency()); }

Target:
public PortfolioItemSummary summarize() { StringBuilder buf = new StringBuilder(96); IborCapFloorLeg mainLeg = product.getCapFloorLeg(); buf.append(SummarizerUtils.datePeriod(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); buf.append(' '); buf.append(SummarizerUtils.amount(mainLeg.getCurrency(), mainLeg.getNotional().getInitialValue())); buf.append(' '); if (mainLeg.getPayReceive().isReceive()) { buf.append("Rec "); summarizeMainLeg(mainLeg, buf); buf.append(getPremium().isPresent() ? " / Pay Premium" : (product.getPayLeg().isPresent() ? " / Pay Periodic" : "")); } else { buf.append( getPremium().isPresent() ? "Rec Premium / Pay " : (product.getPayLeg().isPresent() ? "Rec Periodic / Pay " : "")); summarizeMainLeg(mainLeg, buf); } buf.append(" : "); buf.append(SummarizerUtils.dateRange(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); return SummarizerUtils.summary(this, ProductType.IBOR_CAP_FLOOR, buf.toString(), mainLeg.getCurrency()); }
Source:
private List<String> getCommandLines(File file) { try { return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); } catch (IOException e1) { return Collections.emptyList(); } }

Target:
private List<String> getCommandLines(File file) { try { return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalStateException("Failed to process file " + file.getAbsolutePath(), e); } }
Source:
public CompletableFuture<Map<K, V>> getAllAsync(List<K> keys) { Preconditions.checkNotNull(keys); if (keys.isEmpty()) { return CompletableFuture.completedFuture(Collections.EMPTY_MAP); } readMetrics.numGetAlls.inc(); return asyncHelper.execute(keys, readFn::getAllAsync, readMetrics.getAllNs) .handle((result, e) -> { if (e != null) { throw new SamzaException("Failed to get the records for " + keys, e); } else { if (result != null && result.size() != keys.size()) { throw new SamzaException("Received insufficient records for " + keys); } } return result; }); }

Target:
public CompletableFuture<Map<K, V>> getAllAsync(List<K> keys) { Preconditions.checkNotNull(keys); if (keys.isEmpty()) { return CompletableFuture.completedFuture(Collections.EMPTY_MAP); } readMetrics.numGetAlls.inc(); return execute(readRateLimiter, keys, readFn::getAllAsync, readMetrics.getAllNs) .handle((result, e) -> { if (e != null) { throw new SamzaException("Failed to get the records for " + keys, e); } return result; }); }
Source:
public static Collection<Object[]> comparisonParameters() { return Arrays.asList(new Object[][] { { null, null, 0 }, { null, "", -1 }, { "", "", 0 }, { "", "123", -1 }, { "123", "abc", -1 }, { "123", "123", 0 }, { "012", "12", -1 }, { "2", "10", -1 }, { "abc", "abc", 0 }, { "abc", "def", -1 }, { "abc012", "abc012", 0 }, { "abc2", "abc10", -1 }, { "abc012def", "abc012def", 0 }, { "abc012def", "abc012ghi", -1 }, { "abc2def", "abc10def", -1 } }); }

Target:
public static Collection<Object[]> comparisonParameters() { return Arrays.asList(new Object[][] { { null, null, 0 }, { null, "", -1 }, { "", "", 0 }, { "", "123", -1 }, { "123", "123", 0 }, { "123", "456", -1 }, { "12", "123", -1 }, { "012", "12", -1 }, { "2", "10", -1 }, { "123abc", "123abc", 0 }, { "123abc", "456abc", -1 }, { "12abc", "123abc", -1 }, { "012abc", "12abc", -1 }, { "2abc", "10abc", -1 }, { "123", "abc", -1 }, { "abc", "abc", 0 }, { "abc", "def", -1 }, { "ab", "abc", -1 }, { "123abc", "123def", -1 }, { "123ab", "123abc", -1 }, { "abc123", "abc123", 0 }, { "abc123", "def123", -1 }, { "ab123", "abc123", -1 }, { "abc123", "abc456", -1 }, { "abc12", "abc123", -1 }, { "abc012", "abc12", -1 }, { "abc2", "abc10", -1 }, { "abc123def", "abc123def", 0 }, { "abc123def", "abc123ghi", -1 }, { "abc123de", "abc123def", -1 } }); }
Source:
private void updateDictionaryLocked(boolean mutable) { if (data == null) { root = null; internalDict = mutable ? new MutableDictionary() : new Dictionary(); return; } final Database db = getDatabase(); if (db == null) { throw new IllegalStateException(""); } final MRoot newRoot = new MRoot(new DocContext(db, c4Document), data.toFLValue(), isMutable()); root = newRoot; synchronized (db.getLock()) { internalDict = (Dictionary) newRoot.asNative(); } }

Target:
private void updateDictionaryLocked(boolean mutable) { if (data == null) { root = null; internalDict = mutable ? new MutableDictionary() : new Dictionary(); return; } final Database db = getDatabase(); if (db == null) { throw new IllegalStateException(""); } final MRoot newRoot = new MRoot(new DocContext(db, c4Document), data.toFLValue(), mutable); root = newRoot; synchronized (db.getLock()) { internalDict = (Dictionary) newRoot.asNative(); } }
Source:
public void testConfigurationBindingListener() { List<ConfigurationBinding<?>> seenBindings = new ArrayList<>(); Module module = binder -> { ConfigBinder configBinder = configBinder(binder); configBinder.bindConfig(AnotherConfig.class); configBinder.bindConfigurationBindingListener((configurationBinding, configBinder1) -> { seenBindings.add(configurationBinding); configBinder1.bindConfig(Config1.class); configBinder1.bindConfig(Config1.class, MyAnnotation.class); }); }; Injector injector = createInjector(properties, module); verifyConfig(injector.getInstance(Config1.class)); verifyConfig(injector.getInstance(Key.get(Config1.class, MyAnnotation.class))); assertEquals(seenBindings.size(), 3); assertEquals( ImmutableSet.copyOf(seenBindings), ImmutableSet.of( new ConfigurationBinding<>(Key.get(Config1.class), Config1.class, Optional.empty()), new ConfigurationBinding<>(Key.get(Config1.class, MyAnnotation.class), Config1.class, Optional.empty()), new ConfigurationBinding<>(Key.get(AnotherConfig.class), AnotherConfig.class, Optional.empty()))); }

Target:
public void testConfigurationBindingListener() { List<ConfigurationBinding<?>> seenBindings = new ArrayList<>(); Module module = binder -> { ConfigBinder configBinder = configBinder(binder); configBinder.bindConfig(AnotherConfig.class); configBinder.bindConfigurationBindingListener((configurationBinding, callbackConfigBinder) -> { seenBindings.add(configurationBinding); callbackConfigBinder.bindConfig(Config1.class); callbackConfigBinder.bindConfig(Config1.class, MyAnnotation.class); }); }; Injector injector = createInjector(properties, module); verifyConfig(injector.getInstance(Config1.class)); verifyConfig(injector.getInstance(Key.get(Config1.class, MyAnnotation.class))); assertEquals(seenBindings.size(), 3); assertEquals( ImmutableSet.copyOf(seenBindings), ImmutableSet.of( new ConfigurationBinding<>(Key.get(Config1.class), Config1.class, Optional.empty()), new ConfigurationBinding<>(Key.get(Config1.class, MyAnnotation.class), Config1.class, Optional.empty()), new ConfigurationBinding<>(Key.get(AnotherConfig.class), AnotherConfig.class, Optional.empty()))); }
Source:
public void testReadUnencoded() { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.memory().storageType(StorageType.OFF_HEAP); withCacheManager(new CacheManagerCallable( createCacheManager(TestDataSCI.INSTANCE, cfg)) { @Override public void call() { cm.getClassWhiteList().addClasses(Person.class); Cache<String, Person> cache = cm.getCache(); DataConversion conversion = cache.getAdvancedCache().getValueDataConversion(); Function<Object, byte[]> asStored = s -> (byte[]) conversion.convert(s, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM); Person value = new Person(); cache.put("1", value); assertEquals(cache.get("1"), value); Cache<?, ?> unencodedCache = cache.getAdvancedCache().withStorageMediaType(); assertEquals(unencodedCache.get(asStored.apply("1")), asStored.apply(value)); } }); }

Target:
public void testReadUnencoded() { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.memory().storageType(StorageType.OFF_HEAP); withCacheManager(new CacheManagerCallable( createCacheManager(TestDataSCI.INSTANCE, cfg)) { private final DataConversion conversion = cm.getCache().getAdvancedCache().getValueDataConversion(); public Object asStored(Object object) { return conversion.convert(object, APPLICATION_OBJECT, APPLICATION_PROTOSTREAM); } @Override public void call() { cm.getClassWhiteList().addClasses(Person.class); Cache<String, Person> cache = cm.getCache(); Person value = new Person(); cache.put("1", value); assertEquals(cache.get("1"), value); Cache<?, ?> unencodedCache = cache.getAdvancedCache().withStorageMediaType(); assertEquals(unencodedCache.get(asStored("1")), asStored(value)); } }); }
Source:
public DocumentModel createEntryWithoutReferences(Map<String, Object> fieldMap) throws DirectoryException { throw new UnsupportedOperationException(); }

Target:
public DocumentModel createEntryWithoutReferences(Map<String, Object> fieldMap) throws DirectoryException { Object rawId = fieldMap.get(getIdField()); if (rawId == null) { throw new DirectoryException("Missing id"); } String id = String.valueOf(rawId); Map<String, Object> map = data.get(id); if (map != null) { throw new DirectoryException(String.format("Entry with id %s already exists", id)); } map = new HashMap<>(); data.put(id, map); for (Entry<String, Object> e : fieldMap.entrySet()) { String fieldName = e.getKey(); if (!getDirectory().schemaSet.contains(fieldName)) { continue; } map.put(fieldName, e.getValue()); } return getEntry(id); }
Source:
private void setDiskImageActiveBySnapshotType(Map<Guid, DiskImage> diskImageMap, Snapshot snapshot) { DiskImage diskImage = diskImageMap.get(snapshot.getId()); if (diskImage == null) { return; } if (snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW) { diskImage.setActive(true); } else { diskImage.setActive(false); } }

Target:
private void setDiskImageActiveBySnapshotType(Map<Guid, DiskImage> diskImageMap, Snapshot snapshot) { DiskImage diskImage = diskImageMap.get(snapshot.getId()); if (diskImage == null) { return; } diskImage.setActive(snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW); }
Source:
public static Map<String, String> createStructFromLibvirtSecret(LibvirtSecret libvirtSecret) { HashMap<String, String> con = new HashMap<>(); con.put("uuid", libvirtSecret.getId().toString()); con.put("password", libvirtSecret.getValue()); con.put("description", libvirtSecret.getDescription()); con.put("usageType", libvirtSecret.getUsageType().name()); con.put("usageID", String.format("ovirt/%s/%s", libvirtSecret.getProviderId(), libvirtSecret.getId())); return con; }

Target:
public static Map<String, String> createStructFromLibvirtSecret(LibvirtSecret libvirtSecret) { HashMap<String, String> con = new HashMap<>(); con.put("uuid", libvirtSecret.getId().toString()); con.put("password", libvirtSecret.getValue()); con.put("description", libvirtSecret.getDescription()); con.put("usageType", libvirtSecret.getUsageType().name().toLowerCase()); con.put("usageID", String.format("ovirt/%s/%s", libvirtSecret.getProviderId(), libvirtSecret.getId())); return con; }
Source:
public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { delegate.applyState(sender, topologyId, pushTransfer, stateChunks); return null; }

Target:
public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { return delegate.applyState(sender, topologyId, pushTransfer, stateChunks); }
Source:
private MessageContent getMessageContent(MessageValidationWrapper wrapper, Topic topic) { CompiledSchema<Schema> schema = null; byte[] bytes = null; switch (topic.getContentType()) { case JSON: bytes = wrapper.getMessage().getBytes(); break; case AVRO: try { if (Optional.ofNullable(wrapper.getSchemaVersion()).isPresent()) { schema = schemaRepository.getAvroSchema(topic, SchemaVersion.valueOf(wrapper.getSchemaVersion())); } else { schema = schemaRepository.getLatestAvroSchema(topic); } bytes = jsonAvroConverter.convertToAvro(wrapper.getMessage().getBytes(), schema.getSchema()); } catch (AvroConversionException e) { throw new FilteringConversionException("Could not convert to avro message. Please check schema version"); } break; } return new MessageContent.Builder() .withData(bytes) .withContentType(topic.getContentType()) .withSchema(Optional.ofNullable(schema)) .build(); }

Target:
private MessageContent getMessageContent(MessageValidationWrapper wrapper, Topic topic) { CompiledSchema<Schema> schema = null; byte[] bytes = null; switch (topic.getContentType()) { case JSON: bytes = wrapper.getMessage().getBytes(); break; case AVRO: try { if (Optional.ofNullable(wrapper.getSchemaVersion()).isPresent()) { schema = schemaRepository.getAvroSchema(topic, SchemaVersion.valueOf(wrapper.getSchemaVersion())); } else { schema = schemaRepository.getLatestAvroSchema(topic); } bytes = jsonAvroConverter.convertToAvro(wrapper.getMessage().getBytes(), schema.getSchema()); } catch (AvroConversionException e) { throw new FilterValidationException("Could not convert to avro message. Cause: " + e.getMessage()); } break; } return new MessageContent.Builder() .withContent(bytes) .withContentType(topic.getContentType()) .withSchema(Optional.ofNullable(schema)) .build(); }
Source:
public void inStoreLocale() { StoreFixtures.withStore(client(), store -> { final CartDraft cartDraft = CartDraft.of(EUR).withLocale(Locale.GERMAN).withStore(store.toResourceIdentifier()); final Cart cart = client().executeBlocking(CartCreateCommand.of(cartDraft)); final PagedQueryResult<Cart> result = client().executeBlocking(CartInStoreQuery.of(store.getKey()) .plusPredicates(m -> m.is(cart)) .plusPredicates(m -> m.locale().is(Locale.GERMAN))); assertThat(result.getResults()).hasSize(1); assertThat(result.head().get().getId()).isEqualTo(cart.getId()); client().executeBlocking(CartDeleteCommand.of(cart)); }); }

Target:
public void inStoreLocale() { withStore(client(), store -> { final CartDraft cartDraft = CartDraft.of(EUR).withLocale(Locale.GERMAN).withStore(store.toResourceIdentifier()); final Cart cart = client().executeBlocking(CartCreateCommand.of(cartDraft)); final PagedQueryResult<Cart> result = client().executeBlocking(CartInStoreQuery.of(store.getKey()) .plusPredicates(m -> m.is(cart)) .plusPredicates(m -> m.locale().is(Locale.GERMAN))); assertThat(result.getResults()).hasSize(1); assertThat(result.head().get().getId()).isEqualTo(cart.getId()); client().executeBlocking(CartDeleteCommand.of(cart)); }); }