auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void remove(final Session removedSession) { if (doGetSessions().contains(removedSession)) { getOwnedSessions().remove(removedSession); final SessionListener sessListener = sessionsToListeners.get(removedSession); if (sessListener != null) { removedSession.removeListener(sessListener); } sessionsToListeners.remove(removedSession); final Set<SessionManagerListener> listenersToIterate = Sets.newLinkedHashSet(getAllListeners()); for (final SessionManagerListener listener : listenersToIterate) { listener.notifyRemoveSession(removedSession); } this.fireVPSelectionDeselectionEvents(); if (sessionsToListeners.isEmpty()) { <START> if (Platform.isRunning()) { <END> SiriusPlugin.getDefault().getModelAccessorRegistry().dispose(); } } } }</code><technical_language>remark in MigrationService</technical_language>

Target:
public void remove(final Session removedSession) { if (doGetSessions().contains(removedSession)) { getOwnedSessions().remove(removedSession); final SessionListener sessListener = sessionsToListeners.get(removedSession); if (sessListener != null) { removedSession.removeListener(sessListener); } sessionsToListeners.remove(removedSession); final Set<SessionManagerListener> listenersToIterate = Sets.newLinkedHashSet(getAllListeners()); for (final SessionManagerListener listener : listenersToIterate) { listener.notifyRemoveSession(removedSession); } this.fireVPSelectionDeselectionEvents(); if (sessionsToListeners.isEmpty()) { SiriusPlugin.getDefault().getModelAccessorRegistry().dispose(); } } }
Source:
<code>private void addSchemaToConf(JobConf jobConf) { List<String> typeStrs = Arrays.stream(fieldTypes) .map(t -> HiveTypeUtil.toHiveTypeInfo(t, true).toString()) .collect(Collectors.toList()); jobConf.set(IOConstants.COLUMNS, String.join(",", fieldNames)); jobConf.set(IOConstants.COLUMNS_TYPES, String.join(",", typeStrs)); int numPartCol = partitionKeys != null ? partitionKeys.size() : 0; int firstPartColIndex = fieldNames.length - numPartCol; <START> if (numPartCol == 0) { <END> jobConf.set(SCHEMA_EVOLUTION_COLUMNS, jobConf.get(IOConstants.COLUMNS)); jobConf.set(SCHEMA_EVOLUTION_COLUMNS_TYPES, jobConf.get(IOConstants.COLUMNS_TYPES)); } else { jobConf.set(SCHEMA_EVOLUTION_COLUMNS, String.join(",", Arrays.copyOfRange(fieldNames, 0, firstPartColIndex))); jobConf.set(SCHEMA_EVOLUTION_COLUMNS_TYPES, String.join(",", typeStrs.subList(0, firstPartColIndex))); } String readColIDs = Arrays.stream(selectedFields) .filter(i -> i < firstPartColIndex) .mapToObj(String::valueOf) .collect(Collectors.joining(",")); jobConf.set(ColumnProjectionUtils.READ_COLUMN_IDS_CONF_STR, readColIDs); }</code><technical_language>Need this branch? just: jobConf.set(SCHEMA_EVOLUTION_COLUMNS, String.join(",", Arrays.copyOfRange(fieldNames, 0, firstPartColIndex))); jobConf.set(SCHEMA_EVOLUTION_COLUMNS_TYPES, String.join(",", typeStrs.subList(0, firstPartColIndex)));</technical_language>

Target:
private void addSchemaToConf(JobConf jobConf) { List<String> typeStrs = Arrays.stream(fieldTypes) .map(t -> HiveTypeUtil.toHiveTypeInfo(t, true).toString()) .collect(Collectors.toList()); jobConf.set(IOConstants.COLUMNS, String.join(",", fieldNames)); jobConf.set(IOConstants.COLUMNS_TYPES, String.join(",", typeStrs)); int numNonPartCol = fieldNames.length - partitionKeys.size(); jobConf.set(SCHEMA_EVOLUTION_COLUMNS, String.join(",", Arrays.copyOfRange(fieldNames, 0, numNonPartCol))); jobConf.set(SCHEMA_EVOLUTION_COLUMNS_TYPES, String.join(",", typeStrs.subList(0, numNonPartCol))); String readColIDs = Arrays.stream(selectedFields) .filter(i -> i < numNonPartCol) .mapToObj(String::valueOf) .collect(Collectors.joining(",")); jobConf.set(ColumnProjectionUtils.READ_COLUMN_IDS_CONF_STR, readColIDs); }
Source:
<code><START> public File getWorkingDir() { <END> return this.workingDir.toFile(); }</code><technical_language>reason this return Path? new API</technical_language>

Target:
public Path getWorkingDir() { return this.workingDir; }
Source:
<code>public Response previewSnapshot(Action action) { validateParameters(action, "snapshot.id"); TryBackToAllSnapshotsOfVmParameters tryBackParams = new TryBackToAllSnapshotsOfVmParameters(guid, asGuid(action.getSnapshot().getId())); if (action.isSetRestoreMemory()) { tryBackParams.setRestoreMemory(action.isRestoreMemory()); } if (action.isSetDisks()) { Set<Guid> <START> disksGuid = <END> new HashSet<>(); List<DiskImage> disks = getParent().mapDisks(action.getDisks()); if (disks != null) { disksGuid = getDisksGuidSet(disks); } tryBackParams.setDisks(disksGuid); } Response response = doAction(ActionType.TryBackToAllSnapshotsOfVm, tryBackParams, action); return response; }</code><technical_language>fix in BackendSnapshotResource? aboud extracting a method</technical_language>

Target:
public Response previewSnapshot(Action action) { validateParameters(action, "snapshot.id"); TryBackToAllSnapshotsOfVmParameters tryBackParams = new TryBackToAllSnapshotsOfVmParameters(guid, asGuid(action.getSnapshot().getId())); if (action.isSetRestoreMemory()) { tryBackParams.setRestoreMemory(action.isRestoreMemory()); } if (action.isSetDisks()) { List<DiskImage> disks = getParent().mapDisks(action.getDisks()); tryBackParams.setDisks(getDisksGuidSet(disks)); } Response response = doAction(ActionType.TryBackToAllSnapshotsOfVm, tryBackParams, action); return response; }
Source:
<code>public MediaFormat copyAsAdaptive() { <START> return new MediaFormat(id, trackId, mimeType, NO_VALUE, NO_VALUE, durationUs, NO_VALUE, NO_VALUE, <END> NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, null, OFFSET_SAMPLE_RELATIVE, null, true, maxWidth, maxHeight); }</code><technical_language>This is problematic, creating adaptive MediaFormat (i.e. spans multiple individual formats) a non-adaptive (i.e. arbitrary of individual formats), adaptive MediaFormat is id arbitrary individual format use. a places call this method, decide set id null allow a id passed in argument, set some other value, depending sense</technical_language>

Target:
public MediaFormat copyAsAdaptive() { return new MediaFormat(null, mimeType, NO_VALUE, NO_VALUE, durationUs, NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, null, OFFSET_SAMPLE_RELATIVE, null, true, maxWidth, maxHeight); }
Source:
<code>public void test_services_config_port_increment_false() { Microservices node = Microservices.builder().clusterConfig( ClusterConfig.builder() .transportConfig(TransportConfig.builder() .port(3000) .portAutoIncrement(false) .build())) .build(); <START> assertTrue(node.cluster().address().port() == 3000); <END> }</code><technical_language>need shutdown node</technical_language>

Target:
public void test_services_config_port_increment_false() { Microservices node = Microservices.builder().clusterConfig( ClusterConfig.builder() .transportConfig(TransportConfig.builder() .port(3000) .portAutoIncrement(false) .build())) .build(); assertEquals(node.cluster().address().port() , 3000); node.cluster().shutdown(); }
Source:
<code>public void run() { try { Thread.sleep(DELAY); } catch (InterruptedException e) { GlowServer.logger.severe("ShutdownMonitor interrupted"); return; } GlowServer.logger.warning("Still running after shutdown, finding rogue threads..."); final Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces(); for (Map.Entry<Thread, StackTraceElement[]> entry : traces.entrySet()) { final Thread thread = entry.getKey(); final StackTraceElement[] stack = entry.getValue(); if (thread.isDaemon() || !thread.isAlive() || stack.length == 0) { continue; } GlowServer.logger.warning("Rogue thread: " + thread.toString()); for (StackTraceElement trace : stack) { GlowServer.logger.warning("\tat " + trace.toString()); } thread.interrupt(); } <START> System.exit(1000); <END> }</code><technical_language>In cases, System.exit() is rarely want use. This need some thought</technical_language>

Target:
public void run() { try { Thread.sleep(DELAY); } catch (InterruptedException e) { GlowServer.logger.severe("ShutdownMonitor interrupted"); return; } GlowServer.logger.warning("Still running after shutdown, finding rogue threads..."); final Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces(); for (Map.Entry<Thread, StackTraceElement[]> entry : traces.entrySet()) { final Thread thread = entry.getKey(); final StackTraceElement[] stack = entry.getValue(); if (thread.isDaemon() || !thread.isAlive() || stack.length == 0) { continue; } GlowServer.logger.log(Level.WARNING, "Rogue thread: {0}", thread); for (StackTraceElement trace : stack) { GlowServer.logger.log(Level.WARNING, "\tat {0}", trace); } thread.interrupt(); if (thread.isAlive()) { try { thread.join(1000); } catch (InterruptedException ex) { GlowServer.logger.log(Level.SEVERE, ex.getMessage(), ex); } } } System.exit(0); }
Source:
<code>public boolean verifyCorrectAdInMedrec( String acceptableAd, String unacceptableAd ) throws Exception { int refreshNumber = 0; while(refreshNumber < 5) { verifyMedrecPresent(); Dimension acceptableDimension = new Dimension(1, 1); List<WebElement> iframes = presentMD.findElements(By.cssSelector("iframe")); for (WebElement iframe : iframes) { if ( iframe.isDisplayed() &&(iframe.getSize().height >= acceptableDimension.height &&iframe.getSize().width >= acceptableDimension.width) ) { driver.switchTo().frame(iframe); if (checkIfElementOnPage("img[src='" + acceptableAd + "']")) { PageObjectLogging.log( "AdFound", "Expected ad found", true ); return true; } else if (checkIfElementOnPage("img[src='" + unacceptableAd + "']")) { throw new Exception("Found element that was not expected!"); } else { PageObjectLogging.log( "AdNotFound", "Expected ad not found, refreshing the page", true, driver ); <START> refreshNumber = refreshNumber +=1; <END> driver.navigate().refresh(); } } } } return true; }</code><technical_language>1. swap 173 174 line (more logic increase counter refreshing page) 2. refreshNumber += 1; refreshNumber = refreshNumber + 1; combination of :)</technical_language>

Target:
public boolean verifyCorrectAdInMedrec( String acceptableAd, String unacceptableAd ) throws Exception { int refreshNumber = 0; while(refreshNumber < 5) { verifyMedrecPresent(); Dimension acceptableDimension = new Dimension(1, 1); List<WebElement> iframes = presentMD.findElements(By.cssSelector("iframe")); for (WebElement iframe : iframes) { if ( iframe.isDisplayed() &&(iframe.getSize().height >= acceptableDimension.height &&iframe.getSize().width >= acceptableDimension.width) ) { driver.switchTo().frame(iframe); if (checkIfElementOnPage("img[src='" + acceptableAd + "']")) { PageObjectLogging.log( "AdFound", "Expected ad found", true ); return true; } else if (checkIfElementOnPage("img[src='" + unacceptableAd + "']")) { throw new Exception("Found element that was not expected!"); } else { PageObjectLogging.log( "AdNotFound", "Expected ad not found, refreshing the page", true, driver ); driver.navigate().refresh(); refreshNumber += 1; } } } } return true; }
Source:
<code>public static Collection[] findAll(Context context, Integer limit, Integer offset) throws SQLException { TableRowIterator tri = null; try{ String query = "SELECT c.* FROM collection c " + "LEFT JOIN metadatavalue m on (m.resource_id = c.collection_id and m.resource_type_id = ? and m.metadata_field_id = ?) "; <START> if("oracle".equals(ConfigurationManager.getProperty("db.name"))){ <END> query += " ORDER BY cast(m.text_value as varchar2(128))"; }else{ query += " ORDER BY m.text_value"; } query += " limit ? offset ?"; tri = DatabaseManager.query(context, query, Constants.COLLECTION, MetadataField.findByElement(context, MetadataSchema.find(context, MetadataSchema.DC_SCHEMA).getSchemaID(), "title", null).getFieldID(), limit, offset ); } catch (SQLException e) { log.error("Find all Collections offset/limit - ",e); throw e; } List<Collection> collections = new ArrayList<Collection>(); try { while (tri.hasNext()) { TableRow row = tri.next(); Collection fromCache = (Collection) context.fromCache( Collection.class, row.getIntColumn("collection_id")); if (fromCache != null) { collections.add(fromCache); } else { collections.add(new Collection(context, row)); } } } finally { if (tri != null) { tri.close(); } } Collection[] collectionArray = new Collection[collections.size()]; collectionArray = (Collection[]) collections.toArray(collectionArray); return collectionArray; }</code><technical_language>Please ask DatabaseManager.isOracle() instead, everywhere</technical_language>

Target:
public static Collection[] findAll(Context context, Integer limit, Integer offset) throws SQLException { TableRowIterator tri = null; try{ String query = "SELECT c.* FROM collection c " + "LEFT JOIN metadatavalue m on (m.resource_id = c.collection_id and m.resource_type_id = ? and m.metadata_field_id = ?) "; if(DatabaseManager.isOracle()){ query += " ORDER BY cast(m.text_value as varchar2(128))"; }else{ query += " ORDER BY m.text_value"; } query += " limit ? offset ?"; tri = DatabaseManager.query(context, query, Constants.COLLECTION, MetadataField.findByElement(context, MetadataSchema.find(context, MetadataSchema.DC_SCHEMA).getSchemaID(), "title", null).getFieldID(), limit, offset ); } catch (SQLException e) { log.error("Find all Collections offset/limit - ",e); throw e; } List<Collection> collections = new ArrayList<Collection>(); try { while (tri.hasNext()) { TableRow row = tri.next(); Collection fromCache = (Collection) context.fromCache( Collection.class, row.getIntColumn("collection_id")); if (fromCache != null) { collections.add(fromCache); } else { collections.add(new Collection(context, row)); } } } finally { if (tri != null) { tri.close(); } } Collection[] collectionArray = new Collection[collections.size()]; collectionArray = (Collection[]) collections.toArray(collectionArray); return collectionArray; }
Source:
<code>public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) { if (annotationType == null) { return null; } A ann = clazz.getAnnotation(annotationType); if (ann != null) { return ann; } else { <START> while (clazz != null && !JHelper.objectSameReference(clazz, Object.class)) { <END> ann = findAnnotation(clazz, annotationType, new HashSet<>()); if (ann != null) { return ann; } clazz = clazz.getSuperclass(); } return null; } }</code><technical_language>is Object.class, is clear == is uesd</technical_language>

Target:
public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) { if (annotationType == null) { return null; } A ann = clazz.getAnnotation(annotationType); if (ann != null) { return ann; } else { while (clazz != null && clazz != Object.class) { ann = findAnnotation(clazz, annotationType, new HashSet<>()); if (ann != null) { return ann; } clazz = clazz.getSuperclass(); } return null; } }
Source:
<code>protected void renderRootComponent(final HtmlHeaderContainer headerContainer, final HeaderStreamState headerStreamState, final Component rootComponent) { headerContainer.renderHeaderTagBody(headerStreamState); rootComponent.internalRenderHead(headerContainer); <START> if (rootComponent instanceof InlineEnclosure) { <END> InlineEnclosure typedComponent = (InlineEnclosure) rootComponent; final String childId = typedComponent.getChildId(); Component enclosureController = typedComponent.getParent().visitChildren(new IVisitor<Component, Component>() { @Override public void component(Component object, IVisit<Component> visit) { if (object.getId().equals(childId)){ visit.stop(object); } else { visit.dontGoDeeper(); } } }); if (enclosureController != null){ enclosureController.internalRenderHead(headerContainer); } } }</code><technical_language>code good me! extract in method reduce complexity. E.g. renderInlineEnclosure( HtmlHeaderContainer)</technical_language>

Target:
protected void renderRootComponent(final HtmlHeaderContainer headerContainer, final HeaderStreamState headerStreamState, final Component rootComponent) { headerContainer.renderHeaderTagBody(headerStreamState); rootComponent.internalRenderHead(headerContainer); if (rootComponent instanceof InlineEnclosure) { renderInlineEnclosure(headerContainer, (InlineEnclosure) rootComponent); } }
Source:
<code>public Void visitProject(ProjectNode node, Void context) { StringBuilder builder = new StringBuilder(); for (Map.Entry<Symbol, RowExpression> entry : node.getAssignments().entrySet()) { if ((entry.getValue() instanceof VariableReferenceExpression) && ((VariableReferenceExpression) entry.getValue()).getName().equals(entry.getKey().getName())) { continue; } <START> if (isExpression(entry.getValue())) { <END> builder.append(format("%s := %s\\n", entry.getKey(), castToExpression(entry.getValue()))); } else { builder.append(format("%s := %s\\n", entry.getKey(), formatter.formatRowExpression(entry.getValue()))); } } printNode(node, "Project", builder.toString(), NODE_COLORS.get(NodeType.PROJECT)); return node.getSource().accept(this, context); }</code><technical_language>Same; expect this Expression</technical_language>

Target:
public Void visitProject(ProjectNode node, Void context) { StringBuilder builder = new StringBuilder(); for (Map.Entry<VariableReferenceExpression, RowExpression> entry : node.getAssignments().entrySet()) { if ((entry.getValue() instanceof VariableReferenceExpression) && ((VariableReferenceExpression) entry.getValue()).getName().equals(entry.getKey().getName())) { continue; } builder.append(format("%s := %s\\n", entry.getKey(), formatter.formatRowExpression(entry.getValue()))); } printNode(node, "Project", builder.toString(), NODE_COLORS.get(NodeType.PROJECT)); return node.getSource().accept(this, context); }
Source:
<code>String getActiveContainerHost(String containerID) { String activeContainerId = containerID; if (StandbyTaskUtil.isStandbyContainer(containerID)) { activeContainerId = StandbyTaskUtil.getActiveContainerId(containerID); } SamzaResource resource = samzaApplicationState.pendingProcessors.get(activeContainerId); if (resource == null) { resource = samzaApplicationState.runningProcessors.get(activeContainerId); } if (resource != null) { return resource.getHost(); } <START> return null; <END> }</code><technical_language>return optional instead of null? force callers handle non-existent case of a host for a container id</technical_language>

Target:
Optional<String> getActiveContainerHost(String containerID) { String activeContainerId = containerID; if (StandbyTaskUtil.isStandbyContainer(containerID)) { activeContainerId = StandbyTaskUtil.getActiveContainerId(containerID); } SamzaResource resource = samzaApplicationState.pendingProcessors.get(activeContainerId); if (resource == null) { resource = samzaApplicationState.runningProcessors.get(activeContainerId); } return Optional.ofNullable(resource) .map(SamzaResource::getHost); }
Source:
<code>public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.RAISE_STMT, ctx -> { RaiseStatement raiseStatement = (RaiseStatement) ctx.syntaxNode(); if (raiseStatement.expressions().isEmpty()) { return; } if (raiseStatement.expressions().get(0).is(Tree.Kind.CALL_EXPR)) { CallExpression callExpression = ((CallExpression) raiseStatement.expressions().get(0)); Expression callee = callExpression.callee(); <START> if (callee.is(Tree.Kind.NAME)) { <END> Symbol calleeSymbol = callExpression.calleeSymbol(); if (!inheritsFromBaseException(calleeSymbol)) { ctx.addIssue(raiseStatement, MESSAGE); } } } if (raiseStatement.expressions().get(0).is(Tree.Kind.NAME)) { Symbol symbol = ((Name) raiseStatement.expressions().get(0)).symbol(); if (!inheritsFromBaseException(symbol)) { ctx.addIssue(raiseStatement, MESSAGE); } } }); }</code><technical_language>alternative check callExpression.calleeSymbol() != null</technical_language>

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.RAISE_STMT, ctx -> { RaiseStatement raiseStatement = (RaiseStatement) ctx.syntaxNode(); if (raiseStatement.expressions().isEmpty()) { return; } if (raiseStatement.expressions().get(0).is(Tree.Kind.CALL_EXPR)) { CallExpression callExpression = ((CallExpression) raiseStatement.expressions().get(0)); Symbol calleeSymbol = callExpression.calleeSymbol(); if (!inheritsFromBaseException(calleeSymbol)) { ctx.addIssue(raiseStatement, MESSAGE); } } if (raiseStatement.expressions().get(0).is(Tree.Kind.NAME)) { Symbol symbol = ((Name) raiseStatement.expressions().get(0)).symbol(); if (!inheritsFromBaseException(symbol)) { ctx.addIssue(raiseStatement, MESSAGE); } } }); }
Source:
<code>public boolean testForEvent(ITmfEvent event) throws AttributeNotFoundException { ITmfStateSystemBuilder ss = fProvider.getAssignedStateSystem(); if (fStateValue != null) { TmfXmlStateValue filter = fStateValue; int quark = -1; for (TmfXmlStateAttribute attribute : filter.getAttributes()) { quark = attribute.getAttributeQuark(event, quark); if (quark == -1) { <START> throw new AttributeNotFoundException(); <END> } } ITmfStateValue valueXML; valueXML = filter.getValue(event); ITmfStateValue valueState; if (quark != -1) { valueState = ss.queryOngoingState(quark); } else { valueState = filter.getEventField(event); } return valueXML.equals(valueState); } else if (!fConditions.isEmpty()) { if (fOperator == ConditionOperators.OP_EQUALS) { return fConditions.get(0).testForEvent(event); } else if (fOperator == ConditionOperators.OP_NOT) { return !fConditions.get(0).testForEvent(event); } else if (fOperator == ConditionOperators.OP_AND) { boolean test = true; for (TmfXmlCondition childCondition : fConditions) { test = test && childCondition.testForEvent(event); if (!test) { break; } } return test; } else if (fOperator == ConditionOperators.OP_OR) { boolean test = false; for (TmfXmlCondition childCondition : fConditions) { test = test || childCondition.testForEvent(event); if (test) { break; } } return test; } } return true; }</code><technical_language>this case throw exception if attribute is chose <then> <else> condition</technical_language>

Target:
public boolean testForEvent(ITmfEvent event) throws AttributeNotFoundException { ITmfStateSystemBuilder ss = fProvider.getAssignedStateSystem(); if (fStateValue != null) { TmfXmlStateValue filter = fStateValue; int quark = -1; for (TmfXmlStateAttribute attribute : filter.getAttributes()) { quark = attribute.getAttributeQuark(event, quark); if (quark == -1) { throw new AttributeNotFoundException(); } } ITmfStateValue valueXML; valueXML = filter.getValue(event); ITmfStateValue valueState; if (quark != -1) { valueState = ss.queryOngoingState(quark); } else { valueState = filter.getEventField(event); } return valueXML.equals(valueState); } else if (!fConditions.isEmpty()) { if (fOperator == ConditionOperators.OP_NOT) { return !fConditions.get(0).testForEvent(event); } else if (fOperator == ConditionOperators.OP_AND) { boolean test = true; for (TmfXmlCondition childCondition : fConditions) { test = test && childCondition.testForEvent(event); if (!test) { break; } } return test; } else if (fOperator == ConditionOperators.OP_OR) { boolean test = false; for (TmfXmlCondition childCondition : fConditions) { test = test || childCondition.testForEvent(event); if (test) { break; } } return test; } } else { throw new IllegalStateException("TmfXmlCondition: the condition should be either a state value or be the result of a condition tree"); } return true; }
Source:
<code>public static Set<Method> getAvailableMethods(Class<?> clazz) { Map<String, Set<Method>> methods = Maps.newHashMap(); for (final Method declaredMethod : clazz.getDeclaredMethods()) { appendMethod(methods, declaredMethod); } Class<?> parent = clazz.getSuperclass(); <START> while (null != parent && (!Object.class.equals(parent))) { <END> Set<Map.Entry<String, Set<Method>>> extractedMethods = extractMethods(clazz, parent, methods).entrySet(); for (Map.Entry<String, Set<Method>> extractedMethod : extractedMethods){ Set<Method> m = methods.get(extractedMethod.getKey()); if (m == null) { methods.put(extractedMethod.getKey(), extractedMethod.getValue()); } else { m.addAll(extractedMethod.getValue()); } } parent = parent.getSuperclass(); } Set<Method> returnValue = Sets.newHashSet(); for (Set<Method> each : methods.values()) { returnValue.addAll(each); } return returnValue; }</code><technical_language>For performance reason, avoid double check: java if (parent != null) { while (!Object.class.equals(parent)) { ... } }</technical_language>

Target:
public static Set<Method> getAvailableMethods(Class<?> clazz) { Map<String, Set<Method>> methods = Maps.newHashMap(); for (final Method declaredMethod : clazz.getDeclaredMethods()) { appendMethod(methods, declaredMethod); } Class<?> parent = clazz.getSuperclass(); if (null != parent) { while (!Object.class.equals(parent)) { Set<Map.Entry<String, Set<Method>>> extractedMethods = extractMethods(clazz, parent, methods).entrySet(); for (Map.Entry<String, Set<Method>> extractedMethod : extractedMethods) { Set<Method> m = methods.get(extractedMethod.getKey()); if (m == null) { methods.put(extractedMethod.getKey(), extractedMethod.getValue()); } else { m.addAll(extractedMethod.getValue()); } } parent = parent.getSuperclass(); } } Set<Method> returnValue = Sets.newHashSet(); for (Set<Method> each : methods.values()) { returnValue.addAll(each); } return returnValue; }
Source:
<code>private boolean authorize(String userName) throws UserStoreException { UserStoreManager authorizer; boolean isAuthorized = false; try { authorizer = userRealm.getUserStoreManager(); } catch (UserStoreException e) { String msg = "Cannot get authorizer from Realm"; log.error(msg, e); throw new SecurityException(msg, e); } List<String> userRoleslist = Arrays.asList(authorizer.getRoleListOfUser(userName)); if(userRoleslist.contains("JMXMonitorRole")){ <START> roleName = "JMXMonitorRole"; <END> isAuthorized = true; } else if(userRoleslist.contains("JMXControlRole")){ roleName = "JMXControlRole"; isAuthorized = true; } return isAuthorized; }</code><technical_language>move role names constants</technical_language>

Target:
private String authorize(String userName) throws UserStoreException { AuthorizationManager authorizationManager = userRealm.getAuthorizationManager(); String roleName = null; if (authorizationManager != null) { if (authorizationManager.isUserAuthorized(userName, JMX_USER_READWRITE_PERMISSION, UI_EXECUTE)) { roleName = JMX_CONTROL_ROLE; } else if (authorizationManager.isUserAuthorized(userName, JMX_USER_READONLY_PERMISSION, UI_EXECUTE)) { roleName = JMX_MONITOR_ROLE; } if (roleName != null) { audit.info("User: " + userName + " successfully authorized as " + roleName + " to perform JMX operations."); return roleName; } else { throw new SecurityException("User: " + userName + " not authorized to perform JMX operations."); } } throw new UserStoreException("Unable to retrieve Authorization manager to perform authorization"); }
Source:
<code>public void testAmend() { DiskImage disk = createDiskImage(); disk.setVolumeFormat(VolumeFormat.COW); disk.setQcowCompat(QcowCompat.QCOW2_V2); disk.setDiskAlias("Test"); disk.setDiskDescription("Test_Desc"); when(diskDao.get(diskImageGuid)).thenReturn(disk); disk.setQcowCompat(QcowCompat.QCOW2_V3); command.getParameters().setDiskInfo(disk); initializeCommand(); doNothing().when(command).amendDiskImage(); mockVdsCommandSetVolumeDescription(); <START> command.executeVmCommand(); <END> }</code><technical_language>please verify amend function is executed</technical_language>

Target:
public void testAmend() { DiskImage oldDisk = createDiskImage(); oldDisk.setVolumeFormat(VolumeFormat.COW); oldDisk.setQcowCompat(QcowCompat.QCOW2_V2); oldDisk.setDiskAlias("Test"); oldDisk.setDiskDescription("Test_Desc"); when(diskDao.get(diskImageGuid)).thenReturn(oldDisk); DiskImage newDisk = DiskImage.copyOf(oldDisk); newDisk.setQcowCompat(QcowCompat.QCOW2_V3); command.getParameters().setDiskInfo(newDisk); initializeCommand(); doNothing().when(command).amendDiskImage(); mockVdsCommandSetVolumeDescription(); command.executeVmCommand(); verify(command, times(1)).amendDiskImage(); }
Source:
<code>public void showChangesModal() { clickAndWait(changesModal); <START> PageObjectLogging.log("wikiDiff", "modal with changes is displayed", true); <END> }</code><technical_language>change parameter passed PageObjectLogging.log() "wikiDiff" "showChangesModal"</technical_language>

Target:
public void showChangesModal() { clickAndWait(changesModal); PageObjectLogging.log("changesModal", "modal with changes is displayed", true); }
Source:
<code><START> public ObaUserClient(String obaBaseUrl) { <END> log.debug("Instantiating ObaUserClient with obaBaseUrl " + obaBaseUrl); try { ObaApi.getDefaultContext().setBaseUrl(obaBaseUrl); } catch (URISyntaxException e) { log.error("ObaBaseUrl we constructed was invalid: " + e.getMessage()); } catch (Exception e) { log.error("Exception setting ObaBaseUrl: " + e.getMessage()); throw e; } }</code><technical_language>passing this method, argument, return of getObaBaseUrl(). currently returns String null, leading occasional error crash</technical_language>

Target:
public ObaUserClient(String obaBaseUrl) throws URISyntaxException { log.debug("Instantiating ObaUserClient with obaBaseUrl " + obaBaseUrl); try { ObaApi.getDefaultContext().setBaseUrl(obaBaseUrl); } catch (URISyntaxException e) { log.error("ObaBaseUrl we constructed was invalid: " + e.getMessage()); throw e; } catch (Exception e) { log.error("Exception setting ObaBaseUrl: " + e.getMessage()); throw e; } }
Source:
<code>public void wdlNoTask() throws IOException{ File file = new File(ResourceHelpers.resourceFilePath("noTask.wdl")); File json = new File(ResourceHelpers.resourceFilePath("hello.json")); ArrayList<String> args = new ArrayList<String>() {{ add("--entry"); add(file.getAbsolutePath()); add("--local-entry"); add("--json"); add(json.getAbsolutePath()); }}; WorkflowsApi api = mock(WorkflowsApi.class); UsersApi usersApi = mock(UsersApi.class); Client client = new Client(); client.setConfigFile(ResourceHelpers.resourceFilePath("config")); exit.expectSystemExit(); WorkflowClient workflowClient = new WorkflowClient(api, usersApi, client); workflowClient.checkEntryFile(file.getAbsolutePath(), args, null); <START> Assert.assertTrue("output should include a successful cromwell run",systemOutRule.getLog().contains("Required fields that are missing from WDL file : 'task'")); <END> }</code><technical_language>error message sense. test expects exit WDL file is missing fields. message output include a successful run</technical_language>

Target:
public void wdlNoTask() throws IOException{ File file = new File(ResourceHelpers.resourceFilePath("noTask.wdl")); File json = new File(ResourceHelpers.resourceFilePath("hello.json")); ArrayList<String> args = new ArrayList<String>() {{ add("--entry"); add(file.getAbsolutePath()); add("--local-entry"); add("--json"); add(json.getAbsolutePath()); }}; WorkflowsApi api = mock(WorkflowsApi.class); UsersApi usersApi = mock(UsersApi.class); Client client = new Client(); client.setConfigFile(ResourceHelpers.resourceFilePath("config")); exit.expectSystemExit(); WorkflowClient workflowClient = new WorkflowClient(api, usersApi, client); workflowClient.checkEntryFile(file.getAbsolutePath(), args, null); Assert.assertTrue("output should include an error message and exit",systemOutRule.getLog().contains("Required fields that are missing from WDL file : 'task'")); }
Source:
<code>public void doAuthoriseWithoutBillingAddress_shouldRespondAuthorisationSuccess() { providerWillAuthorise(); AuthCardDetails authCardDetails = AuthCardDetailsBuilder.anAuthCardDetails() .withAddress(null) <START> .build(); <END> GatewayResponse response = cardAuthorisationService.doAuthorise(charge.getExternalId(), authCardDetails); assertThat(response.isSuccessful(), is(true)); assertThat(response.getSessionIdentifier().isPresent(), is(true)); assertThat(response.getSessionIdentifier().get(), is(SESSION_IDENTIFIER)); assertThat(charge.getProviderSessionId(), is(SESSION_IDENTIFIER)); assertThat(charge.getStatus(), is(AUTHORISATION_SUCCESS.getValue())); assertThat(charge.getGatewayTransactionId(), is(TRANSACTION_ID)); verify(mockedChargeEventDao).persistChargeEventOf(charge, Optional.empty()); assertThat(charge.get3dsDetails(), is(nullValue())); assertThat(charge.getCardDetails(), is(notNullValue())); assertThat(charge.getCardDetails().getBillingAddress(), is(nullValue())); assertThat(charge.getCorporateSurcharge().isPresent(), is(false)); }</code><technical_language>This is inconsistent other tests assuming want gradually move AuthCardDetailsBuilder AuthUtils (how end ways build objects?!)</technical_language>

Target:
public void doAuthoriseWithoutBillingAddress_shouldRespondAuthorisationSuccess() { providerWillAuthorise(); AuthCardDetails authCardDetails = AuthCardDetailsFixture.anAuthCardDetails() .withAddress(null) .build(); GatewayResponse response = cardAuthorisationService.doAuthorise(charge.getExternalId(), authCardDetails); assertThat(response.isSuccessful(), is(true)); assertThat(response.getSessionIdentifier().isPresent(), is(true)); assertThat(response.getSessionIdentifier().get(), is(SESSION_IDENTIFIER)); assertThat(charge.getProviderSessionId(), is(SESSION_IDENTIFIER)); assertThat(charge.getStatus(), is(AUTHORISATION_SUCCESS.getValue())); assertThat(charge.getGatewayTransactionId(), is(TRANSACTION_ID)); verify(mockedChargeEventDao).persistChargeEventOf(charge, Optional.empty()); assertThat(charge.get3dsDetails(), is(nullValue())); assertThat(charge.getCardDetails(), is(notNullValue())); assertThat(charge.getCardDetails().getBillingAddress(), is(nullValue())); assertThat(charge.getCorporateSurcharge().isPresent(), is(false)); }
Source:
<code>public SubclassInjectionLoader() { Object lookup; Method privateLookupIn; try { Class<?> methodHandles = Class.forName("java.lang.invoke.MethodHandles"); <START> lookup = methodHandles.getMethod("lookup").invoke(null); <END> privateLookupIn = methodHandles.getMethod("privateLookupIn", Class.class, Class.forName("java.lang.invoke.MethodHandles$Lookup")); } catch (Exception ignored) { lookup = null; privateLookupIn = null; } this.lookup = lookup; this.privateLookupIn = privateLookupIn; }</code><technical_language>For consistency 'getStrategy' impact reduction wrap contents of constructor with: if (ClassInjector.UsingLookup.isAvailable()) { ..</technical_language>

Target:
SubclassInjectionLoader() { if (!Boolean.getBoolean("org.mockito.internal.simulateJava11") && ClassInjector.UsingReflection.isAvailable()) { this.loader = new WithReflection(); } else if (ClassInjector.UsingLookup.isAvailable()) { this.loader = tryLookup(); } else { throw new MockitoException(join(ERROR_MESSAGE, "", Platform.describe())); } }
Source:
<code><START> private static RpcManager blockUntilRemoteNodesRespond(final CheckPoint checkPoint, Cache<?, ?> cache) { <END> RpcManager realManager = TestingUtil.extractComponent(cache, RpcManager.class); RpcManager spy = spy(realManager); doAnswer(invocation -> Mocks.blockingCompletableFuture(() -> { try { return (CompletableFuture) invocation.callRealMethod(); } catch (Throwable throwable) { throw new AssertionError(throwable); } }, checkPoint).call() ).when(spy).invokeRemotelyAsync(anyCollection(), any(StreamIteratorRequestCommand.class), any()); TestingUtil.replaceComponent(cache, RpcManager.class, spy, true); return realManager; }</code><technical_language>void</technical_language>

Target:
private static void blockUntilRemoteNodesRespond(final CheckPoint checkPoint, Cache<?, ?> cache) { RpcManager realManager = TestingUtil.extractComponent(cache, RpcManager.class); RpcManager spy = spy(realManager); doAnswer(invocation -> Mocks.blockingCompletableFuture(() -> { try { return (CompletableFuture) invocation.callRealMethod(); } catch (Throwable throwable) { throw new AssertionError(throwable); } }, checkPoint).call() ).when(spy).invokeRemotelyAsync(anyCollection(), any(StreamIteratorRequestCommand.class), any()); TestingUtil.replaceComponent(cache, RpcManager.class, spy, true); }
Source:
<code>public static List<CredentialsProvider> enabled() { List<CredentialsProvider> providers = <START> new ArrayList<>(ExtensionList.lookup(CredentialsProvider.class)); providers.removeIf(p -> !p.isEnabled()); <END> return providers; }</code><technical_language>Sure, time permits</technical_language>

Target:
public static List<CredentialsProvider> enabled() { return ExtensionList.lookup(CredentialsProvider.class) .stream() .filter(CredentialsProvider::isEnabled) .collect(Collectors.toList()); }
Source:
<code>private void updateVmNamesMap(String editedName) { <START> if (getEditedVmId() == null) { <END> VM vm = getEntity().getVm(); getVmNamesMap().put(vm.getId(), vm.getName()); return; } getVmNamesMap().put(getEditedVmId(), editedName); }</code><technical_language>do need save name if edited</technical_language>

Target:
private void updateVmNamesMap(String editedName) { if (editedVmId == null) { VM vm = getEntity().getVm(); vmNamesMap.put(vm.getId(), vm.getName()); return; } vmNamesMap.put(editedVmId, editedName); }
Source:
<code>protected static SqlParts selectStatementForTextClause(Object clause, String indexName) { if (clause == null) { return null; } if (indexName == null || indexName.isEmpty()) { return null; } if (!(clause instanceof Map)) { return null; } Map<String, Object> textClause = (Map<String, Object>) clause; Map<String, String> searchClause = (Map<String, String>) textClause.get(TEXT); String tableName = IndexManager.tableNameForIndex(indexName); String search = searchClause.get(SEARCH); search = search.replace("'", "''"); <START> String sql = String.format("SELECT _id FROM \"%s\" WHERE %s MATCH ?", tableName, tableName); <END> return SqlParts.partsForSql(sql, new String[]{ search }); }</code><technical_language>This a specific Locale</technical_language>

Target:
protected static SqlParts selectStatementForTextClause(Object clause, String indexName) { if (clause == null) { return null; } if (indexName == null || indexName.isEmpty()) { return null; } if (!(clause instanceof Map)) { return null; } Map<String, Object> textClause = (Map<String, Object>) clause; Map<String, String> searchClause = (Map<String, String>) textClause.get(TEXT); String tableName = IndexManager.tableNameForIndex(indexName); String search = searchClause.get(SEARCH); search = search.replace("'", "''"); String sql = String.format(Locale.ENGLISH, "SELECT _id FROM \"%s\" WHERE \"%s\" MATCH ?", tableName, tableName); return SqlParts.partsForSql(sql, new String[]{ search }); }
Source:
<code><START> Response prepareTransaction() throws Exception { <END> checkConfigurationAndTransactionManager(); PrepareTransactionContext context = (PrepareTransactionContext) operationDecodeContext; if (context.isEmpty()) { if (isTrace) { log.tracef("Transaction %s is read only.", context.getXid()); } return createTransactionResponse(header, XAResource.XA_RDONLY); } PrepareTransactionDecodeContext txContext = new PrepareTransactionDecodeContext(cache, context.getXid()); Response response = checkExistingTxForPrepare(txContext); if (response != null) { if (isTrace) { log.tracef("Transaction %s conflicts with another node. Response is %s", context.getXid(), response); } return response; } if (!txContext.startTransaction()) { if (isTrace) { log.tracef("Unable to start transaction %s", context.getXid()); } return decoder.createNotExecutedResponse(header, null); } AdvancedCache<byte[], byte[]> readCache = cache.withFlags(Flag.FORCE_WRITE_LOCK); boolean failed = false; int xaCode = XAResource.XA_OK; try { for (TransactionWrite write : context.writes()) { if (isValid(write, readCache)) { if (write.isRemove()) { cache.remove(write.key); } else { cache.put(write.key, write.value, buildMetadata(write.lifespan, write.maxIdle)); } } else { failed = true; break; } } } catch (Exception e) { failed = true; throw e; } finally { EmbeddedTransactionManager.dissociateTransaction(); if (failed) { txContext.rollback(); xaCode = XAException.XA_RBROLLBACK; } else if (!txContext.prepare(context.isOnePhaseCommit())) { xaCode = XAException.XA_RBROLLBACK; } } return createTransactionResponse(header, xaCode); }</code><technical_language>I handle exceptions..</technical_language>

Target:
Response prepareTransaction() { validateConfiguration(); PrepareTransactionContext context = (PrepareTransactionContext) operationDecodeContext; if (context.isEmpty()) { if (isTrace) { log.tracef("Transaction %s is read only.", context.getXid()); } return createTransactionResponse(header, XAResource.XA_RDONLY); } PrepareTransactionDecodeContext txContext = new PrepareTransactionDecodeContext(cache, context.getXid()); Response response = checkExistingTxForPrepare(txContext); if (response != null) { if (isTrace) { log.tracef("Transaction %s conflicts with another node. Response is %s", context.getXid(), response); } return response; } if (!txContext.startTransaction()) { if (isTrace) { log.tracef("Unable to start transaction %s", context.getXid()); } return decoder.createNotExecutedResponse(header, null); } AdvancedCache<byte[], byte[]> txCache = txContext.decorateCache(cache); try { for (TransactionWrite write : context.writes()) { if (isValid(write, txCache)) { if (write.isRemove()) { txCache.remove(write.key); } else { txCache.put(write.key, write.value, buildMetadata(write.lifespan, write.maxIdle)); } } else { txContext.setRollbackOnly(); break; } } int xaCode = txContext.prepare(context.isOnePhaseCommit()); return createTransactionResponse(header, xaCode); } catch (Exception e) { return createTransactionResponse(header, txContext.rollback()); } finally { EmbeddedTransactionManager.dissociateTransaction(); } }
Source:
<code>public static synchronized BlockCacheManager getInstance(AccumuloConfiguration conf) throws Exception { if (null == manager) { String impl = conf.get(Property.TSERV_CACHE_FACTORY_IMPL); Class<? extends BlockCacheManager> clazz = AccumuloVFSClassLoader.loadClass(impl, BlockCacheManager.class); <START> manager = (BlockCacheManager) clazz.newInstance(); <END> LOG.info("Created new block cache manager of type: {}", clazz.getSimpleName()); } return manager; }</code><technical_language>I in favor of removing this static. I necessary. I if tserver wants instance, a reference it. current static stuff is troublesome move it. rename this method newInstance if drop static</technical_language>

Target:
public static synchronized BlockCacheManager getInstance(AccumuloConfiguration conf) throws Exception { String impl = conf.get(Property.TSERV_CACHE_MANAGER_IMPL); Class<? extends BlockCacheManager> clazz = AccumuloVFSClassLoader.loadClass(impl, BlockCacheManager.class); LOG.info("Created new block cache manager of type: {}", clazz.getSimpleName()); return (BlockCacheManager) clazz.newInstance(); }
Source:
<code>private ByteBuf decodeStruct(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { <START> HeaderDecoder headerDecoder = new StructHeaderDecoder(v2MaxHeaderSize); <END> return headerDecoder.decode(ctx, buffer); }</code><technical_language>do need create a new instance everytime ? I easily create re-use life-time of HAProxyMessageDecoder</technical_language>

Target:
private ByteBuf decodeStruct(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { if (headerExtractor == null) { headerExtractor = new StructHeaderExtractor(v2MaxHeaderSize); } return headerExtractor.extract(ctx, buffer); }
Source:
<code>public Date getEndDate() { <START> return _responseBuilder.startOfNextDay(endDate == null ? new Date() : endDate); <END> }</code><technical_language>Dates mutable, a copy of endDate passed _responseBuilder.startOfNextDay avoid downstream side effects</technical_language>

Target:
public Date getEndDate() { return _responseBuilder.startOfNextDay(endDate == null ? new Date() : new Date(endDate.getTime())); }
Source:
<code>protected IStatus run(IProgressMonitor monitor) { IStatus status = Status.OK_STATUS; try { SubmoduleWalk walk = SubmoduleWalk.forIndex(repo); boolean refresh = false; while (walk.next() && !monitor.isCanceled()) { for (StagingEntry entry : nodes) { boolean isSubmodule = entry.getPath().equals( walk.getPath()); entry.setSubmodule(isSubmodule); if (isSubmodule) refresh = true; } } if (refresh) stagingView.refreshViewersPreservingExpandedElements(); } catch (IOException e) { status = Activator.createErrorStatus( UIText.StagingViewContentProvider_SubmoduleError, e); <START> } <END> return status; }</code><technical_language>again, if monitor is cancelled, job return Status.CANCEL_STATUS. user cancel *and* exception, avoid complicated logic nice return catch block write if(monitor.isCancelled()) return Status.CANCEL_STATUS; return Status.OK_STATUS;</technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { try { SubmoduleWalk walk = SubmoduleWalk.forIndex(repo); boolean refresh = false; while (walk.next() && !monitor.isCanceled()) { for (StagingEntry entry : nodes) { boolean isSubmodule = entry.getPath().equals( walk.getPath()); entry.setSubmodule(isSubmodule); if (isSubmodule) refresh = true; } } if (refresh) stagingView.refreshViewersPreservingExpandedElements(); } catch (IOException e) { return Activator.createErrorStatus( UIText.StagingViewContentProvider_SubmoduleError, e); } if (monitor.isCanceled()) return Status.CANCEL_STATUS; return Status.OK_STATUS; }
Source:
<code><START> public void updateAllInTransaction(Collection<VmDevice> vmDeviceToSave) { <END> updateAllInBatch("updatevmdynamic", vmDeviceToSave, new MapSqlParameterMapper<VmDevice>() { @Override public MapSqlParameterSource map(VmDevice entity) { MapSqlParameterSource paramValue = new MapSqlParameterSource(); paramValue.addValue("device_id", entity.getDeviceId()); paramValue.addValue("vm_id", entity.getVmId()); paramValue.addValue("address", entity.getAddress()); paramValue.addValue("alias", entity.getAlias()); return paramValue; } }); }</code><technical_language>This entire method is redundant. do is implement updarteAllInBatch(Collection<T>) in MassOperationGenericDAO in a similar fashion updateAll(Collection<T>) call there. point in this type of method in DAOs</technical_language>

Target:
public void updateAllInTransaction(Collection<VmDevice> vmDeviceToSave) { updateAllInBatch("updatevmdynamic", vmDeviceToSave, new MapSqlParameterMapper<VmDevice>() { @Override public MapSqlParameterSource map(VmDevice entity) { MapSqlParameterSource paramValue = new MapSqlParameterSource() .addValue("device_id", entity.getDeviceId()) .addValue("vm_id", entity.getVmId()) .addValue("address", entity.getAddress()) .addValue("alias", entity.getAlias()); return paramValue; } }); }
Source:
<code>public void run() { final Manufacturer manufacturer = this.findManufacturer(this.manufacturerName); if (manufacturer == null) { return; } final List<DeviceModel> deviceModels = this.findDeviceModels(manufacturer); if (deviceModels == null || deviceModels.isEmpty()) { return; } final List<Device> devices = this.findDevices(deviceModels); if (devices.isEmpty()) { return; } final Map<Device, Event> map = this.findEventsForDevices(devices); if (map.isEmpty()) { return; } <START> final List<Device> devicesToContact = new ArrayList<>(); <END> final DateTime maxAge = DateTime.now(DateTimeZone.UTC).minusHours(this.maximumAllowedAge); for (final Entry<Device, Event> entry : map.entrySet()) { if (this.isEventOlderThanMaxInterval(maxAge, entry.getValue())) { LOGGER.info("Found device which has events older than: {}", maxAge); devicesToContact.add(entry.getKey()); } } for (final Device device : devicesToContact) { final ProtocolRequestMessage protocolRequestMessage = this.createProtocolRequestMessage(device); if (protocolRequestMessage != null) { try { LOGGER.info("Attempting to contact device: {}", device.getDeviceIdentification()); this.deviceRequestMessageService.processMessage(protocolRequestMessage); } catch (final FunctionalException e) { LOGGER.error("Exception during sending of protocol request message", e); } } } }</code><technical_language>current approach results in a query Kaifa device. more efficient DB do filtering. of solution: add index (device, date_time) search more efficient</technical_language>

Target:
public void run() { final Manufacturer manufacturer = this.findManufacturer(this.manufacturerName); if (manufacturer == null) { return; } final List<DeviceModel> deviceModels = this.findDeviceModels(manufacturer); if (deviceModels == null || deviceModels.isEmpty()) { return; } final List<Device> devices = this.findDevices(deviceModels); if (devices.isEmpty()) { return; } final List<Device> devicesToContact = this.findDevicesToContact(devices); if (devicesToContact.isEmpty()) { return; } this.contactDevices(devicesToContact); }