auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void pressShortcut(Control control, Runnable pressShortcut, KeyStroke... keys) { AtomicInteger keysPressed = new AtomicInteger(); AtomicInteger keysReleased = new AtomicInteger(); KeyListener keyListener = new KeyListener() { @Override public void keyPressed(KeyEvent e) { keysPressed.incrementAndGet(); } @Override public void keyReleased(KeyEvent e) { keysReleased.incrementAndGet(); } }; <START> UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { <END> control.addKeyListener(keyListener); } }); pressShortcut.run(); new SWTBot().waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return keysPressed.get() > 0 && keysPressed.get() == keysReleased.get(); } @Override public String getFailureMessage() { return "key press " + Arrays.toString(keys) + " not detected"; } }); UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { control.removeKeyListener(keyListener); } }); }</code><technical_language>lambda</technical_language>

Target:
private static void pressShortcut(Control control, Runnable pressShortcut, KeyStroke... keys) { AtomicInteger keysPressed = new AtomicInteger(); AtomicInteger keysReleased = new AtomicInteger(); KeyListener keyListener = new KeyListener() { @Override public void keyPressed(KeyEvent e) { keysPressed.incrementAndGet(); } @Override public void keyReleased(KeyEvent e) { keysReleased.incrementAndGet(); } }; UIThreadRunnable.syncExec(() -> control.addKeyListener(keyListener)); pressShortcut.run(); new SWTBot().waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return keysPressed.get() > 0 && keysPressed.get() == keysReleased.get(); } @Override public String getFailureMessage() { return "key press " + Arrays.toString(keys) + " not detected"; } }); UIThreadRunnable.syncExec(() -> control.removeKeyListener(keyListener)); }
Source:
<code>public void endpointsByNamespaceWithNodeName() { <START> endpointsByNamespaceWithNodePublicIp(); <END> kubernetesClient = newKubernetesClient(true); String forbiddenBody = "\"reason\":\"Forbidden\""; stub("/api/v1/nodes/node-name-1", 403, forbiddenBody); stub("/api/v1/nodes/node-name-2", 403, forbiddenBody); List<Endpoint> result = kubernetesClient.endpoints(); assertThat(format(result), containsInAnyOrder(ready("192.168.0.25", 5701), ready("172.17.0.5", 5702))); assertThat(formatPublic(result), containsInAnyOrder(ready("node-name-1", 31916), ready("node-name-2", 31917))); }</code><technical_language>call another test in this test, is right. Please extract common parts a method reuse</technical_language>

Target:
public void endpointsByNamespaceWithNodeName() { kubernetesClient = newKubernetesClient(true); stub(String.format("/api/v1/namespaces/%s/pods", NAMESPACE), podsListResponse()); stub(String.format("/api/v1/namespaces/%s/endpoints", NAMESPACE), endpointsListResponse()); stub(String.format("/api/v1/namespaces/%s/services/service-0", NAMESPACE), nodePortService1Response()); stub(String.format("/api/v1/namespaces/%s/services/service-1", NAMESPACE), nodePortService2Response()); String forbiddenBody = "\"reason\":\"Forbidden\""; stub("/api/v1/nodes/node-name-1", 403, forbiddenBody); stub("/api/v1/nodes/node-name-2", 403, forbiddenBody); List<Endpoint> result = kubernetesClient.endpoints(); assertThat(format(result), containsInAnyOrder(ready("192.168.0.25", 5701), ready("172.17.0.5", 5702))); assertThat(formatPublic(result), containsInAnyOrder(ready("node-name-1", 31916), ready("node-name-2", 31917))); }
Source:
<code>private String getEditedAtText(String lastEditorEmail, Instant createdAt, Instant lastEditedAt) { if (lastEditedAt == null || lastEditedAt.equals(createdAt)) { return ""; } <START> String lastEditor = commentGiverEmailToNameTable.get(lastEditorEmail) == null ? lastEditorEmail <END> : commentGiverEmailToNameTable.get(lastEditorEmail); boolean isGiverAnonymous = Const.DISPLAYED_NAME_FOR_ANONYMOUS_PARTICIPANT.equals(commentGiverName); return "(last edited " + (isGiverAnonymous ? "" : "by " + SanitizationHelper.sanitizeForHtml(lastEditor) + " ") + "at " + TimeHelper.formatDateTimeForDisplay(lastEditedAt, sessionTimeZone) + ")"; }</code><technical_language>Do save lastEditorEmail for feedback participant</technical_language>

Target:
private String getEditedAtText(String lastEditorEmail, Instant createdAt, Instant lastEditedAt) { if (lastEditedAt == null || lastEditedAt.equals(createdAt)) { return ""; } boolean isGiverAnonymous = Const.DISPLAYED_NAME_FOR_ANONYMOUS_PARTICIPANT.equals(commentGiverName); return "(last edited " + (isGiverAnonymous ? "" : "by " + SanitizationHelper.sanitizeForHtml(commentGiverEmailToNameTable.get(lastEditorEmail)) + " ") + "at " + TimeHelper.formatDateTimeForDisplay(lastEditedAt, sessionTimeZone) + ")"; }
Source:
<code><START> private AuthenticationCache lookupAuthenticationCache() { <END> AuthenticationCache authCache = GeoServerExtensions.bean(AuthenticationCache.class); if (authCache==null) { Disposer disposer = GeoServerExtensions.bean(Disposer.class); authCache = new GuavaAuthenticationCacheImpl(1000); if(disposer!=null) { disposer.register((DisposableBean)authCache); } else { LOGGER.warning("Disposer not available to register for disposal. GuavaAuthenticationCacheImpl may not be closed at application shutdown."); } } return authCache; }</code><technical_language>Strictly speaking this is API change IMHO, ok :)</technical_language>

Target:
AuthenticationCache lookupAuthenticationCache() { AuthenticationCache authCache = GeoServerExtensions.bean(AuthenticationCache.class); return authCache != null ? authCache : new GuavaAuthenticationCacheImpl(1000); }
Source:
<code>private boolean statusFilter(RejisPartialCitation partialCitation){ <START> boolean keepCitation = false; <END> if (!partialCitation.caseStatus.equals("C")){ keepCitation = true; } return keepCitation; }</code><technical_language>I care this method is stinking simple leave 6 lines. it: return !partialCitation.caseStatus.equals("C")</technical_language>

Target:
private boolean statusFilter(RejisPartialCitation partialCitation){ return !partialCitation.caseStatus.equals("C"); }
Source:
<code>public void test(TestHarness th) { <START> th.check(overridden(), 2); <END> }</code><technical_language>check test case override property is set a methodInfo</technical_language>

Target:
public void test(TestHarness th) { th.check(overridden(), 2); th.check(overridden(), 2); }
Source:
<code>public static JavaTypeQualifiedName ofClass(Class<?> clazz) { if (clazz == null) { return null; } String name = clazz.getName(); if (name.indexOf('.') < 0) { name = '.' + name; } <START> return ((JavaTypeQualifiedName) ofString(name)).withClassLoader(clazz.getClassLoader()); <END> }</code><technical_language>this fail expected classloader. auxclasspath refers auxclasspath entries, PMD classloader parent (which allows load JRE classes). So, if this is a JRE class, getClassLoader a reference auxclasspath classloader. exists a scenario this matter, moving a JRE class domain care..</technical_language>

Target:
public static JavaTypeQualifiedName ofClass(Class<?> clazz) { if (clazz == null) { return null; } String name = clazz.getName(); if (name.indexOf('.') < 0) { name = '.' + name; } JavaTypeQualifiedName qualifiedName = (JavaTypeQualifiedName) ofString(name); if (qualifiedName != null) { qualifiedName.withClassLoader(clazz.getClassLoader()); } return qualifiedName; }
Source:
<code>public boolean isRestricted() { <START> throw new UnsupportedOperationException("Not supported yet."); END> }</code><technical_language>Oops</technical_language>

Target:
public boolean isRestricted() { return true; @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer m = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld world; int x; int z; if (args.length == 1) { MCLocation l = ObjectGenerator.GetGenerator().location(args[0], m != null ? m.getWorld() : null, t); world = l.getWorld(); x = l.getBlockX(); z = l.getBlockZ(); } else if (args.length == 2) { if (args[1] instanceof CArray) { world = Static.getServer().getWorld(args[0].val()); MCLocation l = ObjectGenerator.GetGenerator().location(args[1], null, t); x = l.getBlockX(); z = l.getBlockZ(); } else { if (m == null) { throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t); } world = m.getWorld(); x = Static.getInt32(args[0], t); z = Static.getInt32(args[1], t); } } else { world = Static.getServer().getWorld(args[0].val()); x = Static.getInt32(args[1], t); z = Static.getInt32(args[2], t); } world.unloadChunk(x, z); return new CVoid(t); } @Override public String getName() { return "unload_chunk"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public String docs() { return "void {[world], x, z | [world], locationArray} Unloads the chunk, using the specified world, or the current" + " players world if not provided."; } @Override public Version since() { return CHVersion.V3_3_1; } }
Source:
<code>public boolean canUnload() { <START> return false; <END> }</code><technical_language>reason this unloaded</technical_language>

Target:
public boolean canUnload() { return true; }
Source:
<code>protected List<ExecutionErrorInfo> findErrorsToAck(EntityManager em) { List<ExecutionErrorInfo> errorsToAck = new ArrayList<>(); String findProcessErrorsQuery = "select error from ExecutionErrorInfo error " + "where error.acknowledged =:acknowledged " + "and error.processInstanceId in (select pil.id from ProcessInstanceLog pil where status in (:status))"; List<ExecutionErrorInfo> processErrorsToAck = em.createQuery(findProcessErrorsQuery) .setParameter("acknowledged", false) <START> .setParameter("status", Arrays.asList(2, 3)) <END> .getResultList(); errorsToAck.addAll(processErrorsToAck); String findNodeErrorsQuery = "select error from ExecutionErrorInfo error " + "where error.acknowledged =:acknowledged " + "and error.initActivityId in (select nil.nodeInstanceId from NodeInstanceLog nil where nil.processInstanceId = error.processInstanceId and nil.nodeInstanceId = error.initActivityId and nil.type = 1)"; List<ExecutionErrorInfo> nodeErrorsToAck = em.createQuery(findNodeErrorsQuery) .setParameter("acknowledged", false) .getResultList(); errorsToAck.addAll(nodeErrorsToAck); return errorsToAck; }</code><technical_language>replace 2, 3 ProcessInstance.STATE_COMPLETED, ProcessInstance.STATE_ABORTED</technical_language>

Target:
protected List<ExecutionErrorInfo> findErrorsToAck(EntityManager em) { List<ExecutionErrorInfo> errorsToAck = new ArrayList<>(); String findProcessErrorsQuery = "select error from ExecutionErrorInfo error " + "where error.acknowledged =:acknowledged " + "and error.processInstanceId in (select pil.id from ProcessInstanceLog pil where status in (:status))"; List<ExecutionErrorInfo> processErrorsToAck = em.createQuery(findProcessErrorsQuery) .setParameter("acknowledged", new Short("0")) .setParameter("status", Arrays.asList(ProcessInstance.STATE_COMPLETED, ProcessInstance.STATE_ABORTED)) .getResultList(); errorsToAck.addAll(processErrorsToAck); String findNodeErrorsQuery = "select error from ExecutionErrorInfo error " + "where error.acknowledged =:acknowledged " + "and error.initActivityId in (select nil.nodeInstanceId from NodeInstanceLog nil where nil.processInstanceId = error.processInstanceId and nil.nodeInstanceId = error.initActivityId and nil.type = 1)"; List<ExecutionErrorInfo> nodeErrorsToAck = em.createQuery(findNodeErrorsQuery) .setParameter("acknowledged", new Short("0")) .getResultList(); errorsToAck.addAll(nodeErrorsToAck); return errorsToAck; }
Source:
<code>private List<Double> applyScenarios(ObservableId id, double value, ScenarioDefinition scenarioDefinition) { Optional<PerturbationMapping<?>> mapping = scenarioDefinition.getMappings().stream() <START> .filter(m -> m.getFilter().apply(id, value)) <END> .findFirst(); if (mapping.isPresent()) { return mapping.get().getPerturbations().stream() .map(perturbation -> (Double) perturbation.apply(value)) .collect(toImmutableList()); } else { return Collections.nCopies(scenarioDefinition.getScenarioCount(), value); } }</code><technical_language>PerturbationMapping a matches method similar avoid pull out filter call low-level apply method</technical_language>

Target:
private Result<List<Double>> applyScenarios(ObservableId id, double value, ScenarioDefinition scenarioDefinition) { try { Optional<PerturbationMapping<?>> mapping = scenarioDefinition.getMappings().stream() .filter(m -> m.matches(id, value)) .findFirst(); if (mapping.isPresent()) { List<Double> values = mapping.get().getPerturbations().stream() .map(perturbation -> (Double) perturbation.apply(value)) .collect(toImmutableList()); return Result.success(values); } else { List<Double> values = Collections.nCopies(scenarioDefinition.getScenarioCount(), value); return Result.success(values); } } catch (RuntimeException e) { return Result.failure(e); } }
Source:
<code>private Optional<CurrentWsResponse.Homepage> projectHomepage(DbSession dbSession, UserDto user) { Optional<ComponentDto> projectOptional = ofNullable(dbClient.componentDao().selectByUuid(dbSession, of(user.getHomepageParameter()).orElse(EMPTY)).orNull()); <START> if (!projectOptional.isPresent() || !userSession.hasComponentPermission(USER, projectOptional.get())) { <END> cleanUserHomepageInDb(dbSession, user); return empty(); } CurrentWsResponse.Homepage.Builder homepage = CurrentWsResponse.Homepage.newBuilder() .setType(CurrentWsResponse.HomepageType.valueOf(user.getHomepageType())) .setComponent(projectOptional.get().getKey()); setNullable(projectOptional.get().getBranch(), homepage::setBranch); return of(homepage.build()); }</code><technical_language>suggestion: extract in a method, named for example shouldCleanProjectHomepage</technical_language>

Target:
private Optional<CurrentWsResponse.Homepage> projectHomepage(DbSession dbSession, UserDto user) { Optional<ComponentDto> projectOptional = ofNullable(dbClient.componentDao().selectByUuid(dbSession, of(user.getHomepageParameter()).orElse(EMPTY)).orNull()); if (shouldCleanProjectHomepage(projectOptional)) { cleanUserHomepageInDb(dbSession, user); return empty(); } CurrentWsResponse.Homepage.Builder homepage = CurrentWsResponse.Homepage.newBuilder() .setType(CurrentWsResponse.HomepageType.valueOf(user.getHomepageType())) .setComponent(projectOptional.get().getKey()); setNullable(projectOptional.get().getBranch(), homepage::setBranch); return of(homepage.build()); }
Source:
<code>public void getAssignmentValue_multiple() throws Exception { CompilationUnitTree tree = parse("<?php $a = 1;\n$a = 2;", PHPLexicalGrammar.COMPILATION_UNIT); SymbolTable symbolTable = SymbolTableImpl.create(tree); AssignmentExpressionVisitor assignmentExpressionVisitor = new AssignmentExpressionVisitor(symbolTable); tree.accept(assignmentExpressionVisitor); IdentifierTree var = ((SymbolTableImpl) symbolTable).getSymbols("$a").get(0).declaration(); <START> assertThat(assignmentExpressionVisitor.getAssignmentValue(var).isPresent()).isFalse(); <END> }</code><technical_language>find a factorize code 3 test cases</technical_language>

Target:
public void getAssignmentValue_multiple() throws Exception { Optional<ExpressionTree> uniqueAssignedValue = UniqueAssignedValue.Of("$a").from("<?php $a = 1;\n$a = 2;"); assertThat(uniqueAssignedValue).isNotPresent(); }
Source:
<code>protected void setUp() { edgeWeights = new HashMap<>(); nev = edgeWeights::get; dg = NetworkBuilder.directed().allowsParallelEdges(true).allowsSelfLoops(true).build(); <START> for (double[] dg_distance : dg_distances) { <END> dg.addNode(vertexFactoryDG.get()); } did = Indexer.create(dg.nodes(), 1); Integer[] dgArray = new Integer[edges.length]; addEdges(dg, did, dgArray); ug = NetworkBuilder.undirected().allowsParallelEdges(true).allowsSelfLoops(true).build(); for (double[] ugDistance : ug_distances) { ug.addNode(vertexFactoryUG.get()); } uid = Indexer.create(ug.nodes(), 1); Integer[] ugArray = new Integer[edges.length]; addEdges(ug, uid, ugArray); edgeArrays = new HashMap<>(); edgeArrays.put(dg, dgArray); edgeArrays.put(ug, ugArray); }</code><technical_language>I in this case (or line 492) a good idea this a foreach loop. This is _anything_ dg_distances array; "do [X] times elements in dg_distances array". is: need a dg_distance variable, creating a bit odd</technical_language>

Target:
protected void setUp() { edgeWeights = new HashMap<>(); nev = edgeWeights::get; dg = NetworkBuilder.directed().allowsParallelEdges(true).allowsSelfLoops(true).build(); for (int i = 0; i < dg_distances.length; i++) { dg.addNode(vertexFactoryDG.get()); } did = Indexer.create(dg.nodes(), 1); Integer[] dgArray = new Integer[edges.length]; addEdges(dg, did, dgArray); ug = NetworkBuilder.undirected().allowsParallelEdges(true).allowsSelfLoops(true).build(); for (int i = 0; i < ug_distances.length; i++) { ug.addNode(vertexFactoryUG.get()); } uid = Indexer.create(ug.nodes(), 1); Integer[] ugArray = new Integer[edges.length]; addEdges(ug, uid, ugArray); edgeArrays = new HashMap<>(); edgeArrays.put(dg, dgArray); edgeArrays.put(ug, ugArray); }
Source:
<code>private void parseMetadataOptions(String metadataOptions) { try { JSONObject jsonObject = new JSONObject(metadataOptions); JSONArray optionsArray = jsonObject.getJSONArray("MetadataOptions"); JSONObject options = optionsArray.getJSONObject(0); metadataType = options.getString("Type"); metadataFormat = options.getString("Format"); metadataLabel = options.getString("Label"); MetadataElement metadataElement = new MetadataElement(); metadataElement.setElements(metadataType, metadataFormat, metadataLabel); metadataElements.add(metadataElement); } catch (JSONException ex) { <START> OseeCoreException.wrapAndThrow(ex); <END> } }</code><technical_language>If throw exception for metadataoptions there, put MetaDataOptions in default for attribute. I show you</technical_language>

Target:
private void parseMetadataOptions(String metadataOptions) { try { JSONObject jsonObject = new JSONObject(metadataOptions); if (!jsonObject.has("MetadataOptions")) { return; } JSONArray optionsArray = jsonObject.getJSONArray("MetadataOptions"); JSONObject options = optionsArray.getJSONObject(0); metadataType = options.getString("Type"); metadataFormat = options.getString("Format"); metadataLabel = options.getString("Label"); MetadataElement metadataElement = new MetadataElement(); metadataElement.setElements(metadataType, metadataFormat, metadataLabel); metadataElements.add(metadataElement); } catch (JSONException ex) { OseeCoreException.wrapAndThrow(ex); } }
Source:
<code>static public void sendNotification(String userId, String message) { <START> logger.debug("sendNotification()"); <END> if (mMyOpenHABService != null) mMyOpenHABService.sendNotification(userId, message, null, null); }</code><technical_language>enhance statement log message (and userid)? omit details purpose</technical_language>

Target:
static public void sendNotification(String userId, String message) { sendNotification(userId, message, null, null); }
Source:
<code><START> protected DiskImage createImage() { <END> final DiskImage diskImage = new DiskImage(); diskImage.setimage_group_id(Guid.NewGuid()); diskImage.setstorage_ids(new ArrayList<Guid>(Arrays.asList(new Guid()))); return diskImage; }</code><technical_language>minor: This private method</technical_language>

Target:
private DiskImage createImage() { final DiskImage diskImage = new DiskImage(); diskImage.setimage_group_id(Guid.NewGuid()); diskImage.setstorage_ids(new ArrayList<Guid>(Arrays.asList(new Guid()))); return diskImage; }
Source:
<code>public ListBoxModel doFillTypeIdItems(@AncestorInPath Item item) { Project project = null; ListBoxModel items = new ListBoxModel().add(""); if(item instanceof Project) { project = (Project) item; final JiraProjectProperty jiraProjectProperty = (JiraProjectProperty) project.getProperty(JiraProjectProperty.class); JiraSite site = jiraProjectProperty.getSite(); JiraSession session = site.getSession(); if (session != null) { for (IssueType type : session.getIssueTypes()) { <START> items.add("[" + site.getName() + "] " + type.getName(), String.valueOf(type.getId())); <END> } } } return items; }</code><technical_language>Do sorting list alphabetically sense? (or putting globally defined sites top?)</technical_language>

Target:
public ListBoxModel doFillTypeIdItems(@AncestorInPath Item item) { Project project = null; ListBoxModel items = new ListBoxModel().add(""); if(item instanceof Project) { project = (Project) item; final JiraProjectProperty jiraProjectProperty = (JiraProjectProperty) project.getProperty(JiraProjectProperty.class); JiraSite site = jiraProjectProperty.getSite(); if(site != null) { JiraSession session = site.getSession(); if (session != null) { for (IssueType type : session.getIssueTypes()) { items.add("[" + site.getName() + "] " + type.getName(), String.valueOf(type.getId())); } } } } return items; }
Source:
<code><START> protected boolean validateForm(String jobName, String jobType, String jobRetries) { <END> boolean valid = true; view.cleanErrorMessages(); if (jobName.isEmpty()) { view.showNameErrorMessage(); valid = false; } if (jobType.isEmpty()) { view.showEmptyTypeErrorMessage(); valid = false; } if (jobRetries.isEmpty()) { view.showRetriesErrorMessage(); valid = false; } return valid; }</code><technical_language>broke arguments list convention :)</technical_language>

Target:
protected boolean validateForm(String jobName, String jobType, String jobRetries) { boolean valid = true; view.cleanErrorMessages(); if (jobName.isEmpty()) { view.showEmptyNameErrorMessage(); valid = false; } if (jobType.isEmpty()) { view.showEmptyTypeErrorMessage(); valid = false; } if (jobRetries.isEmpty()) { view.showEmptyRetriesErrorMessage(); valid = false; } return valid; }
Source:
<code>private void attachEventContextManagingListenersIfRequired(SessionFactoryServiceRegistry serviceRegistry) { @SuppressWarnings("unchecked") Map<Object, Object> settings = serviceRegistry.getService( ConfigurationService.class ).getSettings(); <START> if ( !EventContextManager.isEventContextRequired( serviceRegistry ) ) { <END> return; } EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class ); EventContextManager stateManager = serviceRegistry.getService( EventContextManager.class ); eventListenerRegistry.addDuplicationStrategy( EventContextManagingAutoFlushEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.AUTO_FLUSH ).appendListener( new EventContextManagingAutoFlushEventListener( stateManager ) ); eventListenerRegistry.addDuplicationStrategy( EventContextManagingFlushEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.FLUSH ).appendListener( new EventContextManagingFlushEventListener( stateManager ) ); if ( getIntegrator( JpaIntegrator.class, serviceRegistry ) != null ) { eventListenerRegistry.addDuplicationStrategy( EventContextManagingPersistEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.PERSIST ).appendListener( new EventContextManagingPersistEventListener( stateManager ) ); } }</code><technical_language>passing settings needed before. Good catch</technical_language>

Target:
private void attachEventContextManagingListenersIfRequired(SessionFactoryServiceRegistry serviceRegistry) { if ( !EventContextManager.isEventContextRequired( serviceRegistry ) ) { return; } EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class ); EventContextManager stateManager = serviceRegistry.getService( EventContextManager.class ); eventListenerRegistry.addDuplicationStrategy( EventContextManagingAutoFlushEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.AUTO_FLUSH ).appendListener( new EventContextManagingAutoFlushEventListener( stateManager ) ); eventListenerRegistry.addDuplicationStrategy( EventContextManagingFlushEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.FLUSH ).appendListener( new EventContextManagingFlushEventListener( stateManager ) ); if ( getIntegrator( JpaIntegrator.class, serviceRegistry ) != null ) { eventListenerRegistry.addDuplicationStrategy( EventContextManagingPersistEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.PERSIST ).appendListener( new EventContextManagingPersistEventListener( stateManager ) ); } }
Source:
<code>public void testDocumentClientConnectionPolicy() throws Exception { <START> String proxyHost = "zwus2-proxy.azure.linkedin.com"; <END> int proxyPort = 3128; String[] schemes = {"http", "https"}; for (String scheme : schemes) { String endpoint = scheme + "://mycosmosdb.documents.azure.com/"; String proxyHostProperty = scheme + "." + "proxyHost"; String proxyPortProperty = scheme + "." + "proxyPort"; System.clearProperty(proxyHostProperty); System.clearProperty(proxyPortProperty); ConnectionPolicy policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNull("Expected null proxy", policy.getProxy()); System.setProperty(proxyHostProperty, proxyHost); policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNotNull("Expected proxy", policy.getProxy()); assertEquals("Wrong host", proxyHost, policy.getProxy().getHostName()); assertEquals("Wrong scheme", scheme, policy.getProxy().getSchemeName()); assertEquals("Expected default port", -1, policy.getProxy().getPort()); System.setProperty(proxyPortProperty, String.valueOf(proxyPort)); policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNotNull("Expected proxy", policy.getProxy()); assertEquals("Wrong host", proxyHost, policy.getProxy().getHostName()); assertEquals("Wrong scheme", scheme, policy.getProxy().getSchemeName()); assertEquals("Wrong port", proxyPort, policy.getProxy().getPort()); } }</code><technical_language>linkedin endpoint</technical_language>

Target:
public void testDocumentClientConnectionPolicy() throws Exception { String proxyHost = "azure-proxy.github.com"; int proxyPort = 3128; String[] schemes = {"http", "https"}; for (String scheme : schemes) { String endpoint = scheme + "://mycosmosdb.documents.azure.com/"; String proxyHostProperty = scheme + "." + "proxyHost"; String proxyPortProperty = scheme + "." + "proxyPort"; System.clearProperty(proxyHostProperty); System.clearProperty(proxyPortProperty); ConnectionPolicy policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNull("Expected null proxy", policy.getProxy()); System.setProperty(proxyHostProperty, proxyHost); policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNotNull("Expected proxy", policy.getProxy()); assertEquals("Wrong host", proxyHost, policy.getProxy().getHostName()); assertEquals("Expected default port", -1, policy.getProxy().getPort()); System.setProperty(proxyPortProperty, String.valueOf(proxyPort)); policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNotNull("Expected proxy", policy.getProxy()); assertEquals("Wrong host", proxyHost, policy.getProxy().getHostName()); assertEquals("Wrong port", proxyPort, policy.getProxy().getPort()); } }
Source:
<code>private void assertAnnotation(int numOccurrences, String physicalTableName, String tenant, String schemaName, String logicalTableName, PTableType tableType, long ddlTimestamp) throws IOException { <START> int foundCount = 0; <END> int notFoundCount = 0; List<Map<String, byte[]>> entries = getEntriesForTable(TableName.valueOf(physicalTableName)); for (Map<String, byte[]> m : entries) { byte[] tenantBytes = m.get(MutationState.MutationMetadataType.TENANT_ID.toString()); byte[] schemaBytes = m.get(MutationState.MutationMetadataType.SCHEMA_NAME.toString()); byte[] logicalTableBytes = m.get(MutationState.MutationMetadataType.LOGICAL_TABLE_NAME.toString()); byte[] tableTypeBytes = m.get(MutationState.MutationMetadataType.TABLE_TYPE.toString()); byte[] timestampBytes = m.get(MutationState.MutationMetadataType.TIMESTAMP.toString()); assertNotNull(timestampBytes); long timestamp = Bytes.toLong(timestampBytes); if (Objects.equals(tenant, Bytes.toString(tenantBytes)) && Objects.equals(schemaName, Bytes.toString(schemaBytes)) && Objects.equals(logicalTableName, Bytes.toString(logicalTableBytes)) && Objects.equals(tableType.toString(), Bytes.toString(tableTypeBytes)) && Objects.equals(ddlTimestamp, timestamp) && timestamp < HConstants.LATEST_TIMESTAMP) { foundCount++; } else { notFoundCount++; } } Assert.assertEquals(numOccurrences, foundCount); Assert.assertEquals(0, notFoundCount); }</code><technical_language>idea is WAL entry upsert/delete entity (table view) annotation lastDDLTimestamp of entity this a potential schema registry find schema of entity point in time mutation issued it</technical_language>

Target:
private void assertAnnotation(int numOccurrences, String physicalTableName, String tenant, String schemaName, String logicalTableName, PTableType tableType, long ddlTimestamp) throws IOException { int foundCount = 0; int notFoundCount = 0; List<Map<String, byte[]>> entries = getEntriesForTable(TableName.valueOf(physicalTableName)); for (Map<String, byte[]> m : entries) { byte[] tenantBytes = m.get(MutationState.MutationMetadataType.TENANT_ID.toString()); byte[] schemaBytes = m.get(MutationState.MutationMetadataType.SCHEMA_NAME.toString()); byte[] logicalTableBytes = m.get(MutationState.MutationMetadataType.LOGICAL_TABLE_NAME.toString()); byte[] tableTypeBytes = m.get(MutationState.MutationMetadataType.TABLE_TYPE.toString()); byte[] timestampBytes = m.get(MutationState.MutationMetadataType.TIMESTAMP.toString()); assertNotNull(timestampBytes); long timestamp = Bytes.toLong(timestampBytes); if (Objects.equals(tenant, Bytes.toString(tenantBytes)) && Objects.equals(schemaName, Bytes.toString(schemaBytes)) && Objects.equals(logicalTableName, Bytes.toString(logicalTableBytes)) && Objects.equals(tableType.toString(), Bytes.toString(tableTypeBytes)) && Objects.equals(ddlTimestamp, timestamp) && timestamp < HConstants.LATEST_TIMESTAMP) { foundCount++; } else { notFoundCount++; } } assertEquals(numOccurrences, foundCount); assertEquals(0, notFoundCount); }
Source:
<code>public void testAlterTable() <START> throws InterruptedException <END> { assertUpdate("CREATE TABLE test_table (c1 bigint, c2 bigint)"); assertUpdate("INSERT INTO test_table VALUES (1, 1), (1, 2), (1, 3), (1, 4)", 4); assertUpdate("INSERT INTO test_table VALUES (11, 1), (11, 2)", 2); assertUpdate("ALTER TABLE test_table ADD COLUMN c3 bigint"); assertQueryFails("ALTER TABLE test_table DROP COLUMN c3", "Cannot drop the column which has the largest column ID in the table"); assertUpdate("INSERT INTO test_table VALUES (2, 1, 1), (2, 2, 2), (2, 3, 3), (2, 4, 4)", 4); assertUpdate("INSERT INTO test_table VALUES (22, 1, 1), (22, 2, 2), (22, 4, 4)", 3); assertUpdate("DELETE FROM test_table WHERE c1=1 and c2=1", 1); assertUpdate("DELETE FROM test_table WHERE c1=11", 2); assertUpdate("ALTER TABLE test_table DROP COLUMN c2"); assertUpdate("INSERT INTO test_table VALUES (3, 1), (3, 2), (3, 3), (3, 4)", 4); assertUpdate("DELETE FROM test_table WHERE c1=2 and c3=1", 1); assertUpdate("DELETE FROM test_table WHERE c1=22", 3); assertUpdate("DROP TABLE test_table"); }</code><technical_language>If a unit test method needs checked exceptions, throws Exception</technical_language>

Target:
public void testAlterTable() { assertUpdate("CREATE TABLE test_alter_table (c1 bigint, c2 bigint)"); assertUpdate("INSERT INTO test_alter_table VALUES (1, 1), (1, 2), (1, 3), (1, 4)", 4); assertUpdate("INSERT INTO test_alter_table VALUES (11, 1), (11, 2)", 2); assertUpdate("ALTER TABLE test_alter_table ADD COLUMN c3 bigint"); assertQueryFails("ALTER TABLE test_alter_table DROP COLUMN c3", "Cannot drop the column which has the largest column ID in the table"); assertUpdate("INSERT INTO test_alter_table VALUES (2, 1, 1), (2, 2, 2), (2, 3, 3), (2, 4, 4)", 4); assertUpdate("INSERT INTO test_alter_table VALUES (22, 1, 1), (22, 2, 2), (22, 4, 4)", 3); assertUpdate("DELETE FROM test_alter_table WHERE c1 = 1 and c2 = 1", 1); assertUpdate("DELETE FROM test_alter_table WHERE c1 = 11", 2); assertUpdate("ALTER TABLE test_alter_table DROP COLUMN c2"); assertUpdate("INSERT INTO test_alter_table VALUES (3, 1), (3, 2), (3, 3), (3, 4)", 4); assertUpdate("DELETE FROM test_alter_table WHERE c1 = 2 and c3 = 1", 1); assertUpdate("DELETE FROM test_alter_table WHERE c1 = 22", 3); assertUpdate("DROP TABLE test_alter_table"); }
Source:
<code>private String createAccountFileContent( XMPPAccount activeAccount, ArrayList<XMPPAccount> configuredAccounts) { <START> Integer index = configuredAccounts.indexOf(activeAccount); <END> StringBuilder xmlContent = new StringBuilder() .append("<accounts>\n") .append(String.format(" <activeAccountIndex>%d</activeAccountIndex>\n", index)); xmlContent.append(" <configuredAccounts>\n"); for (XMPPAccount acc : configuredAccounts) { xmlContent .append(" <xmppAccount>\n") .append(String.format(" <username>%s</username>\n", acc.getUsername())) .append(String.format(" <password>%s</password>\n", acc.getPassword())) .append(String.format(" <domain>%s</domain>\n", acc.getDomain())) .append(String.format(" <server>%s</server>\n", acc.getServer())) .append(String.format(" <port>%d</port>\n", acc.getPort())) .append(String.format(" <useTLS>%s</useTLS>\n", acc.useTLS())) .append(String.format(" <useSASL>%s</useSASL>\n", acc.useSASL())) .append(" </xmppAccount>\n"); } xmlContent.append(" </configuredAccounts>\n").append("</accounts>"); return xmlContent.toString(); }</code><technical_language>is "int" "integer" want return null. I this multiple times in this patch set</technical_language>

Target:
private String createAccountFileContent( XMPPAccount activeAccount, ArrayList<XMPPAccount> configuredAccounts) { int index = configuredAccounts.indexOf(activeAccount); StringBuilder xmlContent = new StringBuilder() .append("<accounts>\n") .append(String.format(" <activeAccountIndex>%d</activeAccountIndex>\n", index)); xmlContent.append(" <configuredAccounts>\n"); for (XMPPAccount acc : configuredAccounts) { xmlContent .append(" <xmppAccount>\n") .append(String.format(" <username>%s</username>\n", acc.getUsername())) .append(String.format(" <password>%s</password>\n", acc.getPassword())) .append(String.format(" <domain>%s</domain>\n", acc.getDomain())) .append(String.format(" <server>%s</server>\n", acc.getServer())) .append(String.format(" <port>%d</port>\n", acc.getPort())) .append(String.format(" <useTLS>%s</useTLS>\n", acc.useTLS())) .append(String.format(" <useSASL>%s</useSASL>\n", acc.useSASL())) .append(" </xmppAccount>\n"); } xmlContent.append(" </configuredAccounts>\n").append("</accounts>"); return xmlContent.toString(); }
Source:
<code>public void retry() { <START> invoke(next()); <END> }</code><technical_language>assert is executed in correct thread</technical_language>

Target:
public void retry() { context.checkThread(); invoke(next()); }
Source:
<code><START> void processRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { <END> getHandler().handle(msg, ctx, r); }</code><technical_language>![Codacy](<LINK_0> Issue found: [Use explicit scoping instead of default package private level](<LINK_1></technical_language>

Target:
protected void processRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { getHandler().handle(msg, ctx, r); }
Source:
<code>public String loadZip(LoadZipDetails ldz, Locale locale) throws IOException { String realFileName = ""; String returnFileName = ""; <START> OutputStreamWriter writer = null; <END> HttpURLConnection conn = null; InputStream istream = null; OutputStream ostream = null; try { LOGGER.debug("WFS URL: " + ldz.getWFSUrl()); if (ldz.isDownloadNormalWay()) { System.out.println("Download normal way"); } else { System.out.println("Download plugin way"); } if (ldz.getGetFeatureInfoRequest().isEmpty()) { return null; } LOGGER.debug("WFS URL: " + ldz.getWFSUrl()); LOGGER.debug("-- filtter: " + ldz.getGetFeatureInfoRequest()); final URL url = new URL(ldz.getWFSUrl() + ldz.getGetFeatureInfoRequest()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(600000); conn.connect(); String filename = UUID.randomUUID().toString(); istream = conn.getInputStream(); String strTempDir = ldz.getTemporaryDirectory(); File dir0 = new File(strTempDir); dir0.mkdirs(); ostream = new FileOutputStream(new File(dir0, filename + ".zip")); final byte[] buffer = new byte[8 * 1024]; while (true) { int len = istream.read(buffer); if (len <= 0) { break; } ostream.write(buffer, 0, len); } if (!isValid(new File(dir0, filename + ".zip"))) { ErrorReportDetails erd = new ErrorReportDetails(); erd.setErrorFileLocation(realFileName); erd.setWfsUrl(ldz.getWFSUrl()); erd.setXmlRequest(ldz.getGetFeatureInfoRequest()); erd.setUserEmail(ldz.getUserEmail()); erd.setLanguage(locale.getLanguage()); sendErrorReportToEmail(erd); } } catch (Exception ex) { LOGGER.error("Error: ", ex); } finally { IOHelper.close(writer); if (conn != null) { conn.disconnect(); } IOHelper.close(istream); IOHelper.close(ostream); } return returnFileName; }</code><technical_language>This is</technical_language>

Target:
public String loadZip(LoadZipDetails ldz, Locale locale) throws IOException { String realFileName = null; HttpURLConnection conn = null; try { LOGGER.debug("WFS URL: " + ldz.getWFSUrl()); if (ldz.isDownloadNormalWay()) { LOGGER.debug("Download normal way"); } LOGGER.debug("WFS URL: " + ldz.getWFSUrl()); LOGGER.debug("-- filter: " + ldz.getGetFeatureInfoRequest()); final URL url = new URL(ldz.getWFSUrl() + ldz.getGetFeatureInfoRequest()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(600000); conn.connect(); String filename = UUID.randomUUID().toString(); String strTempDir = ldz.getTemporaryDirectory(); File dir0 = new File(strTempDir); dir0.mkdirs(); try (InputStream istream = conn.getInputStream(); OutputStream ostream = new FileOutputStream(new File(dir0, filename + ".zip"))) { IOHelper.copy(istream, ostream); realFileName = new File(dir0, filename + ".zip").getAbsolutePath(); } } catch (Exception ex) { LOGGER.error("Error: ", ex); } return realFileName; }
Source:
<code>public static ConnectionBuilder connection() { Class<? extends ConnectionBuilder> clazz = null; try { clazz = (Class<ConnectionBuilder>) Class.forName("org.ovirt.engine.sdk4.internal.ConnectionBuilder45"); } catch <START> (ClassNotFoundException|LinkageError ex) { <END> try { clazz = (Class<ConnectionBuilder>) Class.forName("org.ovirt.engine.sdk4.internal.ConnectionBuilder42"); } catch (ClassNotFoundException|LinkageError e) { throw new Error("No connection implementation found", e); } } try { return clazz.newInstance(); } catch (Exception e) { throw new Error("Failed to initialize connection implementation", e); } }</code><technical_language>catch "Throwable". a good practice in general, I is acceptable in this case</technical_language>

Target:
public static ConnectionBuilder connection() { Class<? extends ConnectionBuilder> clazz = null; try { clazz = (Class<ConnectionBuilder>) Class.forName("org.ovirt.engine.sdk4.internal.ConnectionBuilder45"); } catch (Throwable ex) { try { clazz = (Class<ConnectionBuilder>) Class.forName("org.ovirt.engine.sdk4.internal.ConnectionBuilder42"); } catch (Throwable e) { throw new Error("No connection implementation found", e); } } try { return clazz.newInstance(); } catch (Exception e) { throw new Error("Failed to initialize connection implementation", e); } }
Source:
<code>private void relocateHashAdder(JsonObject hashAdder){ Set<JsonObject> parents = GraphUtilities.getUpstream(hashAdder, graph); if (parents.size() != 1) return; JsonObject parent = parents.iterator().next(); if (GraphUtilities.getDownstream(parent, graph).size() != 1) return; <START> if (jstring(parent, "kind").equals(BVirtualMarker.END_PARALLEL.kind())) { <END> GraphUtilities.removeOperator(hashAdder, graph); GraphUtilities.addBefore(parent, hashAdder, graph); } }</code><technical_language>utility methods in graph operators get kind of operator invocation</technical_language>

Target:
private void relocateHashAdder(JsonObject hashAdder){ Set<JsonObject> parents = GraphUtilities.getUpstream(hashAdder, graph); if (parents.size() != 1) return; JsonObject parent = parents.iterator().next(); if (GraphUtilities.isKind(parent, BVirtualMarker.END_PARALLEL.kind()) && GraphUtilities.getDownstream(parent, graph).size() == 1) { JsonObject hashAdderCopy = GraphUtilities.copyOperatorNewName( hashAdder, jstring(hashAdder, "name")); GraphUtilities.removeOperator(hashAdder, graph); GraphUtilities.addBefore(parent, hashAdderCopy, graph); } }
Source:
<code>public void windowsOnly() { <START> assumeTrue(File.pathSeparatorChar==';'); <END> }</code><technical_language>NIT: Functions.isWindows()</technical_language>

Target:
public void windowsOnly() { assumeTrue(Functions.isWindows()); }
Source:
<code>private void loadProviders() { ArrayList<ProviderPair> ret = new ArrayList<ProviderPair>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IConfigurationElement[] cf = registry.getConfigurationElementsFor("org.jboss.tools.openshift.core.connection", "registryprovider"); for( int i = 0; i < cf.length; i++ ) { try { IConnectionRegistryProvider p = (IConnectionRegistryProvider) cf[i].createExecutableExtension("class"); String weight = cf[i].getAttribute("weight"); Integer in = Integer.parseInt(weight); if( p != null && in != null) { ret.add(new ProviderPair(p, in.intValue())); } } catch (CoreException e) { OpenShiftCoreActivator.pluginLog().logError("Failure loading registry provider extension", e); } } <START> registryProviders = (ProviderPair[]) ret.toArray(new ProviderPair[ret.size()]); <END> }</code><technical_language>![MINOR](<LINK_1> 'Severity: MINOR') Remove this unnecessary cast "ProviderPair[]". [![rule](<LINK_0>](<LINK_2></technical_language>

Target:
private void loadProviders() { ArrayList<ProviderPair> ret = new ArrayList<ProviderPair>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IConfigurationElement[] cf = registry.getConfigurationElementsFor("org.jboss.tools.openshift.core.connection", "registryprovider"); for( int i = 0; i < cf.length; i++ ) { try { IConnectionRegistryProvider p = (IConnectionRegistryProvider) cf[i].createExecutableExtension("class"); String weight = cf[i].getAttribute("weight"); Integer in = Integer.parseInt(weight); if( p != null && in != null) { ret.add(new ProviderPair(p, in.intValue())); } } catch (CoreException e) { OpenShiftCoreActivator.pluginLog().logError("Failure loading registry provider extension", e); } } registryProviders = ret.toArray(new ProviderPair[ret.size()]); }
Source:
<code>static void configureHttpProxy() throws MalformedURLException { for (String protocol : new String[] { "http", "https" }) { <START> if (System.getProperty(protocol + ".proxyHost") != null) continue; <END> String s = System.getenv(protocol + "_proxy"); if (s == null && protocol.equals("https")) { s = System.getenv("HTTPS_PROXY"); } if (s == null || s.equals("")) continue; final URL u = new URL( (s.indexOf("://") == -1) ? protocol + "://" + s : s); if (!u.getProtocol().startsWith("http")) throw new MalformedURLException(MessageFormat.format( CLIText.get().invalidHttpProxyOnlyHttpSupported, s)); final String proxyHost = u.getHost(); final int proxyPort = u.getPort(); System.setProperty(protocol + ".proxyHost", proxyHost); if (proxyPort > 0) System.setProperty(protocol + ".proxyPort", String.valueOf(proxyPort)); final String userpass = u.getUserInfo(); if (userpass != null && userpass.contains(":")) { final int c = userpass.indexOf(':'); final String user = userpass.substring(0, c); final String pass = userpass.substring(c + 1); CachedAuthenticator.add( new CachedAuthenticator.CachedAuthentication(proxyHost, proxyPort, user, pass)); } } }</code><technical_language>nit: add braces 1-liners</technical_language>

Target:
static void configureHttpProxy() throws MalformedURLException { for (String protocol : new String[] { "http", "https" }) { if (System.getProperty(protocol + ".proxyHost") != null) { continue; } String s = System.getenv(protocol + "_proxy"); if (s == null && protocol.equals("https")) { s = System.getenv("HTTPS_PROXY"); } if (s == null || s.equals("")) { continue; } final URL u = new URL( (s.indexOf("://") == -1) ? protocol + "://" + s : s); if (!u.getProtocol().startsWith("http")) throw new MalformedURLException(MessageFormat.format( CLIText.get().invalidHttpProxyOnlyHttpSupported, s)); final String proxyHost = u.getHost(); final int proxyPort = u.getPort(); System.setProperty(protocol + ".proxyHost", proxyHost); if (proxyPort > 0) System.setProperty(protocol + ".proxyPort", String.valueOf(proxyPort)); final String userpass = u.getUserInfo(); if (userpass != null && userpass.contains(":")) { final int c = userpass.indexOf(':'); final String user = userpass.substring(0, c); final String pass = userpass.substring(c + 1); CachedAuthenticator.add( new CachedAuthenticator.CachedAuthentication(proxyHost, proxyPort, user, pass)); } } }
Source:
<code>public GenericRecord parse(ByteBuffer bytes) { Pair<SUBJECT, ID> subjectAndId = subjectAndIdConverter.getSubjectAndId(bytes); Schema schema = typedRepository.getSchema(subjectAndId.lhs, subjectAndId.rhs); if (schema == null) <START> throw new ParseException("schema lookup failed!!!"); <END> DatumReader<GenericRecord> reader = new GenericDatumReader<GenericRecord>(schema); ByteBufferInputStream inputStream = new ByteBufferInputStream(Collections.singletonList(bytes)); try { return reader.read(null, DecoderFactory.get().binaryDecoder(inputStream, null)); } catch (IOException e) { throw new ParseException(e, "Fail to decode avro message!"); } }</code><technical_language>put arguments of getSchema(..) in exception message</technical_language>

Target:
public GenericRecord parse(ByteBuffer bytes) { Pair<SUBJECT, ID> subjectAndId = subjectAndIdConverter.getSubjectAndId(bytes); Schema schema = typedRepository.getSchema(subjectAndId.lhs, subjectAndId.rhs); if (schema == null) { throw new ParseException(String.format("schema lookup failed! subject=%s, id=%s", subjectAndId.lhs, subjectAndId.rhs)); } DatumReader<GenericRecord> reader = new GenericDatumReader<GenericRecord>(schema); ByteBufferInputStream inputStream = new ByteBufferInputStream(Collections.singletonList(bytes)); try { return reader.read(null, DecoderFactory.get().binaryDecoder(inputStream, null)); } catch (IOException e) { throw new ParseException(e, "Fail to decode avro message!"); } }