auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void decorateView(View containerView, View view, IAdaptable semanticAdapter, String semanticHint, int index, boolean persisted) { EObject element = view.getElement(); if (element instanceof DRepresentationDescriptor) { markAsLinkNote(view); } <START> super.decorateView(containerView, view, semanticAdapter, semanticHint, index, persisted); <END> }</code><technical_language>I is call super..decorateView in</technical_language>

Target:
protected void decorateView(View containerView, View view, IAdaptable semanticAdapter, String semanticHint, int index, boolean persisted) { super.decorateView(containerView, view, semanticAdapter, semanticHint, index, persisted); EObject element = view.getElement(); if (element instanceof DRepresentationDescriptor) { markAsLinkNote(view); } }
Source:
<code>void loadINodeDirectorySection(InputStream in) throws IOException { final List<INodeReference> refList = parent.getLoaderContext() .getRefList(); ArrayList<INode> inodeList = new ArrayList<>(); while (true) { INodeDirectorySection.DirEntry e = INodeDirectorySection.DirEntry .parseDelimitedFrom(in); if (e == null) { break; } INodeDirectory p = dir.getInode(e.getParent()).asDirectory(); for (long id : e.getChildrenList()) { INode child = dir.getInode(id); if (addToParent(p, child)) { if (child.isFile()) { inodeList.add(child); } if (inodeList.size() >= 1000) { addToCacheAndBlockMap(inodeList); inodeList.clear(); } } <START> <END> } for (int refId : e.getRefChildrenList()) { INodeReference ref = refList.get(refId); if (addToParent(p, ref)) { if (ref.isFile()) { inodeList.add(ref); } if (inodeList.size() >= 1000) { addToCacheAndBlockMap(inodeList); inodeList.clear(); } } } } addToCacheAndBlockMap(inodeList); }</code><technical_language>empty line</technical_language>

Target:
void loadINodeDirectorySection(InputStream in) throws IOException { final List<INodeReference> refList = parent.getLoaderContext() .getRefList(); ArrayList<INode> inodeList = new ArrayList<>(); while (true) { INodeDirectorySection.DirEntry e = INodeDirectorySection.DirEntry .parseDelimitedFrom(in); if (e == null) { break; } INodeDirectory p = dir.getInode(e.getParent()).asDirectory(); for (long id : e.getChildrenList()) { INode child = dir.getInode(id); if (addToParent(p, child)) { if (child.isFile()) { inodeList.add(child); } if (inodeList.size() >= DIRECTORY_ENTRY_BATCH_SIZE) { addToCacheAndBlockMap(inodeList); inodeList.clear(); } } else { LOG.warn("Failed to add the inode to the directory {}", child.getId(), p.getId()); } } for (int refId : e.getRefChildrenList()) { INodeReference ref = refList.get(refId); if (addToParent(p, ref)) { if (ref.isFile()) { inodeList.add(ref); } if (inodeList.size() >= DIRECTORY_ENTRY_BATCH_SIZE) { addToCacheAndBlockMap(inodeList); inodeList.clear(); } } else { LOG.warn("Failed to add the inode reference to the directory {}", ref.getId(), p.getId()); } } } addToCacheAndBlockMap(inodeList); }
Source:
<code>public static IBlockStateMatcher create(crafttweaker.api.block.IBlockState... blockStates) { <START> if (blockStates == null || blockStates.length == 0) return null; <END> if (blockStates.length == 1) { return new BlockStateMatcher(blockStates[0]); } else { return new BlockStateMatcherOr(Arrays.copyOf(blockStates, blockStates.length)); } }</code><technical_language>Validations mentioned if returning null. if put in bracket handler returns null values end array of 1 null</technical_language>

Target:
public static IBlockStateMatcher create(crafttweaker.api.block.IBlockState... blockStates) { if (blockStates == null) { throw new IllegalArgumentException("Cannot create matcher for null blockstate"); } for (Object o : blockStates) { if (o == null) { throw new IllegalArgumentException("Cannot create matcher for null blockstate"); } } if (blockStates.length == 1) { return new BlockStateMatcher(blockStates[0]); } else { return new BlockStateMatcherOr(Arrays.copyOf(blockStates, blockStates.length)); } }
Source:
<code>public WorkspaceActivityManager( WorkspaceManager workspaceManager, WorkspaceActivityDao activityDao, EventService eventService, @Named("che.limits.workspace.idle.timeout") long timeout) { this.workspaceManager = workspaceManager; this.eventService = eventService; this.activityDao = activityDao; this.defaultTimeout = timeout; if (timeout < MINIMAL_TIMEOUT) { LOG.warn( "Value of property \"che.limits.workspace.idle.timeout\" is below recommended minimum (" + TimeUnit.MILLISECONDS.toMinutes(MINIMAL_TIMEOUT) <START> + " minutes). This may cause problems with workspace components startup and can cause premature workspace shutdown."); <END> } this.workspaceEventsSubscriber = new EventSubscriber<WorkspaceStatusEvent>() { @Override public void onEvent(WorkspaceStatusEvent event) { switch (event.getStatus()) { case RUNNING: try { Workspace workspace = workspaceManager.getWorkspace(event.getWorkspaceId()); if (workspace.getAttributes().remove(WORKSPACE_STOPPED_BY) != null) { workspaceManager.updateWorkspace(event.getWorkspaceId(), workspace); } } catch (Exception ex) { LOG.warn( "Failed to remove stopped information attribute for workspace " + event.getWorkspaceId()); } update(event.getWorkspaceId(), System.currentTimeMillis()); break; case STOPPED: try { activityDao.removeExpiration(event.getWorkspaceId()); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } break; default: } } }; }</code><technical_language>I propose: This problems workspace components startup and/or premature workspace shutdown</technical_language>

Target:
public WorkspaceActivityManager( WorkspaceManager workspaceManager, WorkspaceActivityDao activityDao, EventService eventService, @Named("che.limits.workspace.idle.timeout") long timeout) { this.workspaceManager = workspaceManager; this.eventService = eventService; this.activityDao = activityDao; this.defaultTimeout = timeout; if (timeout < MINIMAL_TIMEOUT) { LOG.warn( "Value of property \"che.limits.workspace.idle.timeout\" is below recommended minimum (" + TimeUnit.MILLISECONDS.toMinutes(MINIMAL_TIMEOUT) + " minutes). This may cause problems with workspace components startup and/or premature workspace shutdown."); } this.workspaceEventsSubscriber = new EventSubscriber<WorkspaceStatusEvent>() { @Override public void onEvent(WorkspaceStatusEvent event) { switch (event.getStatus()) { case RUNNING: try { Workspace workspace = workspaceManager.getWorkspace(event.getWorkspaceId()); if (workspace.getAttributes().remove(WORKSPACE_STOPPED_BY) != null) { workspaceManager.updateWorkspace(event.getWorkspaceId(), workspace); } } catch (Exception ex) { LOG.warn( "Failed to remove stopped information attribute for workspace " + event.getWorkspaceId()); } update(event.getWorkspaceId(), System.currentTimeMillis()); break; case STOPPED: try { activityDao.removeExpiration(event.getWorkspaceId()); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } break; default: } } }; }
Source:
<code>private void syncExec(final Runnable runnable) { final AtomicReference<RuntimeException> exception = new AtomicReference<RuntimeException>(); browser .getDisplay() .syncExec( () -> { try { runnable.run(); } catch (RuntimeException e) { exception.set(e); } <START> }); <END> if (exception.get() != null) { throw exception.get(); } }</code><technical_language>syncExec( () -> {runnable.run(); return null;});</technical_language>

Target:
private void syncExec(final Runnable runnable) { syncExec( () -> { runnable.run(); return null; }); }
Source:
<code>public List<ObjectModel> parse(InputStream inputStream, String streamName) throws InvalidDDFFileException, IOException { streamName = streamName == null ? "" : streamName; LOG.debug("Parsing DDF file {}", streamName); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(inputStream); Version lwm2mVersion; DDFFileValidator ddfFileValidator; if (ddfValidatorFactory != null) { lwm2mVersion = ddfValidatorFactory.extractLWM2MVersion(document, streamName); ddfFileValidator = ddfValidatorFactory.create(lwm2mVersion); } else { lwm2mVersion = null; ddfFileValidator = ddfValidator; } if (ddfFileValidator != null) { ddfFileValidator.validate(document); } ArrayList<ObjectModel> objects = new ArrayList<>(); NodeList nodeList = document.getDocumentElement().getElementsByTagName("Object"); for (int i = 0; i < nodeList.getLength(); i++) { <START> objects.add(parseObject(nodeList.item(i), streamName, lwm2mVersion, ddfValidatorFactory != null)); <END> } return objects; } catch (InvalidDDFFileException | SAXException e) { throw new InvalidDDFFileException(e, "Invalid DDF file %s", streamName); } catch (ParserConfigurationException e) { throw new IllegalStateException("Unable to create Document Builder", e); } }</code><technical_language>ddfFileValidator != null instead of ddfValidatorFactory != null</technical_language>

Target:
public List<ObjectModel> parse(InputStream inputStream, String streamName) throws InvalidDDFFileException, IOException { streamName = streamName == null ? "" : streamName; LOG.debug("Parsing DDF file {}", streamName); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(inputStream); Version lwm2mVersion; DDFFileValidator ddfFileValidator; if (ddfValidatorFactory != null) { lwm2mVersion = ddfValidatorFactory.extractLWM2MVersion(document, streamName); ddfFileValidator = ddfValidatorFactory.create(lwm2mVersion); } else { lwm2mVersion = null; ddfFileValidator = ddfValidator; } boolean validateDdf = ddfFileValidator != null; if (validateDdf) { ddfFileValidator.validate(document); } ArrayList<ObjectModel> objects = new ArrayList<>(); NodeList nodeList = document.getDocumentElement().getElementsByTagName("Object"); for (int i = 0; i < nodeList.getLength(); i++) { objects.add(parseObject(nodeList.item(i), streamName, lwm2mVersion, validateDdf)); } return objects; } catch (InvalidDDFFileException | SAXException e) { throw new InvalidDDFFileException(e, "Invalid DDF file %s", streamName); } catch (ParserConfigurationException e) { throw new IllegalStateException("Unable to create Document Builder", e); } }
Source:
<code>public CommandResult<CanvasViolation> execute(AbstractCanvasHandler context) { ShapeUtils.removeControlPoints(candidate, context, controlPoints); <START> ShapeUtils.hideControlPoints(candidate, context); <END> ShapeUtils.showControlPoints(candidate, context); return buildResult(); }</code><technical_language>hide is remove, inverted</technical_language>

Target:
public CommandResult<CanvasViolation> execute(AbstractCanvasHandler context) { ShapeUtils.hideControlPoints(candidate, context); ShapeUtils.removeControlPoints(candidate, context, controlPoints); ShapeUtils.showControlPoints(candidate, context); return buildResult(); }
Source:
<code>public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException { if (getRoleId() != null && getRoleId() < 1L) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Invalid role id provided"); } List<RolePermission> rolePermissions = roleService.findAllPermissionsBy(getRoleId()); ListResponse<RolePermissionResponse> response = new ListResponse<>(); List<RolePermissionResponse> rolePermissionResponses = new ArrayList<>(); for (RolePermission rolePermission : rolePermissions) { Role role = roleService.findRole(rolePermission.getRoleId()); if (role == null) { continue; } RolePermissionResponse rolePermissionResponse = new RolePermissionResponse(); rolePermissionResponse.setRoleId(role.getUuid()); rolePermissionResponse.setRoleName(role.getName()); rolePermissionResponse.setId(rolePermission.getUuid()); rolePermissionResponse.setRule(rolePermission.getRule()); rolePermissionResponse.setRulePermission(rolePermission.getPermission()); rolePermissionResponse.setDescription(rolePermission.getDescription()); rolePermissionResponse.setObjectName("rolepermission"); rolePermissionResponses.add(rolePermissionResponse); } response.setResponses(rolePermissionResponses); response.setResponseName(getCommandName()); setResponseObject(response); <START> } <END></code><technical_language>create commands: factor out</technical_language>

Target:
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException { final List<RolePermission> rolePermissions = roleService.findAllPermissionsBy(getRoleId()); setupResponse(rolePermissions, getRoleId()); }
Source:
<code>public void fromRelativeURLTest() throws IOException { GeoServerResourceLoader loader = new GeoServerResourceLoader(); tempFolder.create(); File tempDir = tempFolder.getRoot(); loader.setBaseDirectory(tempDir); Resource res = loader.fromURL("file:relative/with/special+characters%23"); <START> assertEquals("relative/with/special characters#", res.path()); <END> try (OutputStream out = res.out()) { out.write("someText".getBytes()); } assertEquals("someText", Files.asCharSource(res.file(), Charset.defaultCharset()).read()); }</code><technical_language>Thanks, check if macOS build passes :)</technical_language>

Target:
public void fromRelativeURLTest() throws IOException { GeoServerResourceLoader loader = new GeoServerResourceLoader(); tempFolder.create(); File tempDir = tempFolder.getRoot(); loader.setBaseDirectory(tempDir); Resource res = loader.fromURL("file:relative/with/special+characters%23%C3%BC"); assertEquals("relative/with/special characters#ü", res.path()); try (OutputStream out = res.out()) { out.write("someText".getBytes()); } assertEquals("someText", Files.asCharSource(res.file(), Charset.defaultCharset()).read()); }
Source:
<code>public void listOnePageOfQueuesFail() throws Exception { MockWebServer server = mockOpenStackServer(); server.enqueue(new MockResponse().setBody(accessRackspace)); server.enqueue(new MockResponse().setResponseCode(404).setBody("")); try { MarconiApi api = api(server.getUrl("/").toString(), "openstack-marconi"); QueueApi queueApi = api.getQueueApiForZoneAndClient("DFW", CLIENT_ID); List<Queue> queues = queueApi.list(false).concat().toList(); <START> assertEquals(queues.size(), 0); <END> } finally { server.shutdown(); } }</code><technical_language>assertTrue(queues.isEmpty(), "Expecting empty queues %s", queues)</technical_language>

Target:
public void listOnePageOfQueuesFail() throws Exception { MockWebServer server = mockOpenStackServer(); server.enqueue(new MockResponse().setBody(accessRackspace)); server.enqueue(new MockResponse().setResponseCode(404)); try { MarconiApi api = api(server.getUrl("/").toString(), "openstack-marconi"); QueueApi queueApi = api.getQueueApiForZoneAndClient("DFW", CLIENT_ID); FluentIterable<Queue> queues = queueApi.list(false).concat(); assertTrue(queues.isEmpty(), "Expecting empty queues but was " + queues.toString()); } finally { server.shutdown(); } }
Source:
<code>private boolean enableButtonSubComponents(Boolean enable) { boolean ingestRunning = IngestManager.getInstance().isIngestRunning(); pnCorrelationProperties.setEnabled(enable && !ingestRunning); bnManageTypes.setEnabled(enable && !ingestRunning); correlationPropertiesTextArea.setEnabled(enable && !ingestRunning); organizationPanel.setEnabled(enable && !ingestRunning); organizationTextArea.setEnabled(enable && !ingestRunning); manageOrganizationButton.setEnabled(enable && !ingestRunning); <START> showCasesButton.setEnabled(enable && !ingestRunning); <END> return true; }</code><technical_language>add labels disabled central repo is disabled</technical_language>

Target:
private boolean enableButtonSubComponents(Boolean enable) { boolean ingestRunning = IngestManager.getInstance().isIngestRunning(); pnCorrelationProperties.setEnabled(enable && !ingestRunning); bnManageTypes.setEnabled(enable && !ingestRunning); correlationPropertiesTextArea.setEnabled(enable && !ingestRunning); organizationPanel.setEnabled(enable && !ingestRunning); organizationTextArea.setEnabled(enable && !ingestRunning); manageOrganizationButton.setEnabled(enable && !ingestRunning); showCasesButton.setEnabled(enable && !ingestRunning); casesPanel.setEnabled(enable && !ingestRunning); casesTextArea.setEnabled(enable && !ingestRunning); return true; }
Source:
<code>public void test() { connect(); click(jq("@button").eq(0)); waitResponse(); <START> System.out.println(jq(".z-listheader-sorticon").eq(2).width()); <END> Assert.assertTrue(jq(".z-listheader-sorticon").eq(2).width() > 0); click(jq("@button").eq(1)); waitResponse(); System.out.println(jq(".z-listheader-sorticon").eq(2).isVisible()); Assert.assertEquals(jq(".z-listheader-sorticon").eq(2).width(), 0); }</code><technical_language>remove</technical_language>

Target:
public void test() { connect(); click(jq("@button").eq(0)); waitResponse(); Assert.assertNotEquals(0, jq(".z-listheader").eq(2).width()); Assert.assertNotEquals(400, jq(".z-listhead").width()); click(jq("@button").eq(1)); waitResponse(); Assert.assertEquals(400, jq(".z-listhead").width()); }
Source:
<code>private EntitySearchFilter createOrderFilter(RestListRequest requestList) { String groupBy = requestList.getSort(); String key = IResourceManager.RESOURCE_DESCR_FILTER_KEY; if ("description".equals(groupBy)) { key = IResourceManager.RESOURCE_DESCR_FILTER_KEY; } else if ("updatedAt".equals(groupBy)) { key = IResourceManager.RESOURCE_MODIFY_DATE_FILTER_KEY; } else if ("createdAt".equals(groupBy)) { key = IResourceManager.RESOURCE_CREATION_DATE_FILTER_KEY; } else if ("name".equals(groupBy)) { key = IResourceManager.RESOURCE_FILENAME_FILTER_KEY; } <START> EntitySearchFilter filter = new EntitySearchFilter(key, true); <END> filter.setOrder(requestList.getDirection().equals(EntitySearchFilter.DESC_ORDER) ? EntitySearchFilter.DESC_ORDER : EntitySearchFilter.ASC_ORDER); return filter; }</code><technical_language>this change do</technical_language>

Target:
private EntitySearchFilter createOrderFilter(RestListRequest requestList) { String groupBy = requestList.getSort(); String key = IResourceManager.RESOURCE_DESCR_FILTER_KEY; if ("description".equals(groupBy)) { key = IResourceManager.RESOURCE_DESCR_FILTER_KEY; } else if ("updatedAt".equals(groupBy)) { key = IResourceManager.RESOURCE_MODIFY_DATE_FILTER_KEY; } else if ("createdAt".equals(groupBy)) { key = IResourceManager.RESOURCE_CREATION_DATE_FILTER_KEY; } else if ("name".equals(groupBy)) { key = IResourceManager.RESOURCE_FILENAME_FILTER_KEY; } else if ("owner".equals(groupBy)) { key = IResourceManager.RESOURCE_OWNER_FILTER_KEY; } EntitySearchFilter filter = new EntitySearchFilter(key, true); filter.setOrder(requestList.getDirection().equals(EntitySearchFilter.DESC_ORDER) ? EntitySearchFilter.DESC_ORDER : EntitySearchFilter.ASC_ORDER); return filter; }
Source:
<code>protected MessageHandler createHandler(Object bean, Method method, List<Annotation> annotations) { String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, "applySequence", String.class); AbstractMessageSplitter splitter; if (AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) { Object target = this.resolveTargetBeanFromMethodWithBeanAnnotation(method); splitter = this.extractTypeIfPossible(target, AbstractMessageSplitter.class); if (splitter == null) { if (target instanceof MessageHandler) { Assert.hasText(applySequence, "'applySequence' can be applied to 'AbstractMessageSplitter', but " + "target handler is: " + target.getClass()); return (MessageHandler) target; } else { splitter = new MethodInvokingSplitter(target); } <START> } <END> } else { splitter = new MethodInvokingSplitter(bean, method); } if (StringUtils.hasText(applySequence)) { String applySequenceValue = this.environment.resolvePlaceholders(applySequence); if (StringUtils.hasText(applySequenceValue)) { splitter.setApplySequence(Boolean.parseBoolean(applySequenceValue)); } } this.setOutputChannelIfPresent(annotations, splitter); return splitter; }</code><technical_language>Filter SA else {return target} router splitter</technical_language>

Target:
protected MessageHandler createHandler(Object bean, Method method, List<Annotation> annotations) { String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, "applySequence", String.class); AbstractMessageSplitter splitter; if (AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) { Object target = this.resolveTargetBeanFromMethodWithBeanAnnotation(method); splitter = this.extractTypeIfPossible(target, AbstractMessageSplitter.class); if (splitter == null) { if (target instanceof MessageHandler) { Assert.hasText(applySequence, "'applySequence' can be applied to 'AbstractMessageSplitter', but " + "target handler is: " + target.getClass()); return (MessageHandler) target; } else { splitter = new MethodInvokingSplitter(target); } } else { return splitter; } } else { splitter = new MethodInvokingSplitter(bean, method); } if (StringUtils.hasText(applySequence)) { String applySequenceValue = this.environment.resolvePlaceholders(applySequence); if (StringUtils.hasText(applySequenceValue)) { splitter.setApplySequence(Boolean.parseBoolean(applySequenceValue)); } } this.setOutputChannelIfPresent(annotations, splitter); return splitter; }
Source:
<code>public static void reportVideoPlayEvent(String videoName, long videoDuration, long videoStartTime) { String videoUsage; if (videoDuration == -1) { <START> videoUsage = VIDEO_USAGE_OTHER; <END> } else { long timeSpend = new Date().getTime() - videoStartTime; timeSpend = timeSpend + VIDEO_USAGE_ERROR_APPROXIMATION; double timeSpendInFraction = timeSpend / videoDuration; if (timeSpendInFraction <= 0.25) { videoUsage = VIDEO_USAGE_IMMEDIATE; } else if (timeSpendInFraction <= 0.5) { videoUsage = VIDEO_USAGE_PARTIAL; } else if (timeSpendInFraction <= 0.75) { videoUsage = VIDEO_USAGE_MOST; } else if (timeSpendInFraction <= 2) { videoUsage = VIDEO_USAGE_FULL; } else { videoUsage = VIDEO_USAGE_OTHER; } } reportEvent(CCAnalyticsEvent.VIEW_QUESTION_MEDIA, new String[]{FirebaseAnalytics.Param.ITEM_ID, CCAnalyticsParam.USER_RETURNED}, new String[]{videoName, videoUsage}); }</code><technical_language>useful this is happening, swallow signal otherwise. Worth adding VIDEO_USAGE_UKNOWN_LENGTH similar</technical_language>

Target:
public static void reportVideoPlayEvent(String videoName, long videoDuration, long videoStartTime) { String videoUsage; if (videoDuration == -1) { videoUsage = VIDEO_USAGE_LENGTH_UNKNOWN; } else { long timeSpend = new Date().getTime() - videoStartTime; timeSpend = timeSpend + VIDEO_USAGE_ERROR_APPROXIMATION; double timeSpendInFraction = timeSpend / videoDuration; if (timeSpendInFraction <= 0.25) { videoUsage = VIDEO_USAGE_IMMEDIATE; } else if (timeSpendInFraction <= 0.5) { videoUsage = VIDEO_USAGE_PARTIAL; } else if (timeSpendInFraction <= 0.75) { videoUsage = VIDEO_USAGE_MOST; } else if (timeSpendInFraction <= 2) { videoUsage = VIDEO_USAGE_FULL; } else { videoUsage = VIDEO_USAGE_OTHER; } } reportEvent(CCAnalyticsEvent.VIEW_QUESTION_MEDIA, new String[]{FirebaseAnalytics.Param.ITEM_ID, CCAnalyticsParam.USER_RETURNED}, new String[]{videoName, videoUsage}); }
Source:
<code>public void unexpectedBodyLength() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http://localhost") .setBody(EXPECTED); <START> StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "4"))) .verifyError(UnexpectedLengthException.class); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "6"))) .verifyError(UnexpectedLengthException.class); <END> }</code><technical_language>validate error message is debug issues. java StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "4"))) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof UnexpectedLengthException); assertTrue(throwable.getMessage().equals("Request body emitted 4 bytes, expected 5 bytes." }); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "6"))) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof UnexpectedLengthException); assertTrue(throwable.getMessage().equals("Request body emitted 6 bytes, more expected 5 bytes." });</technical_language>

Target:
public void unexpectedBodyLength() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http://localhost") .setBody(EXPECTED); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "4"))) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof UnexpectedLengthException); assertEquals("Request body emitted 5 bytes, more than the expected 4 bytes.", throwable.getMessage()); }); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "6"))) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof UnexpectedLengthException); assertEquals("Request body emitted 5 bytes, less than the expected 6 bytes.", throwable.getMessage()); }); }
Source:
<code>public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { String analyticsLabelForPref = prefKeyToAnalyticsEvent.get(key); if (analyticsLabelForPref != null) { GoogleAnalyticsUtils.reportEditPref(GoogleAnalyticsFields.CATEGORY_DEV_PREFS, analyticsLabelForPref, getEditPrefValue(key)); } switch (key) { case ENABLE_AUTO_LOGIN: if (!isAutoLoginEnabled()) { DevSessionRestorer.clearPassword(sharedPreferences); } break; case EDIT_SAVE_SESSION: String sessionString = CommCareApplication.instance().getCurrentApp().getAppPreferences().getString(EDIT_SAVE_SESSION, ""); if (!"".equals(sessionString)) { setSessionStateFromEditText(sessionString); } break; case ENABLE_SAVE_SESSION: if (!isSessionSavingEnabled()) { DevSessionRestorer.clearSession(); } setSessionEditText(); break; <START> case PREFS_CUSTOM_RESTORE_DOC_LOCATION: <END> String filePath = getCustomRestoreDocLocation(); if (!filePath.isEmpty()) { if (FilenameUtils.getExtension(filePath).contentEquals("xml")) { getActivity().setResult(DeveloperPreferences.RESULT_SYNC_CUSTOM); getActivity().finish(); } else { Toast.makeText(getActivity(), Localization.get("file.wrong.type", "xml"), Toast.LENGTH_LONG).show(); } } break; } }</code><technical_language>nice, great move handling of this instead of onActivityResult</technical_language>

Target:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { String analyticsLabelForPref = prefKeyToAnalyticsEvent.get(key); if (analyticsLabelForPref != null) { GoogleAnalyticsUtils.reportEditPref(GoogleAnalyticsFields.CATEGORY_DEV_PREFS, analyticsLabelForPref, getEditPrefValue(key)); } switch (key) { case ENABLE_AUTO_LOGIN: if (!isAutoLoginEnabled()) { DevSessionRestorer.clearPassword(sharedPreferences); } break; case EDIT_SAVE_SESSION: String sessionString = CommCareApplication.instance().getCurrentApp().getAppPreferences().getString(EDIT_SAVE_SESSION, ""); if (!"".equals(sessionString)) { setSessionStateFromEditText(sessionString); } break; case ENABLE_SAVE_SESSION: if (!isSessionSavingEnabled()) { DevSessionRestorer.clearSession(); } setSessionEditText(); break; case PREFS_CUSTOM_RESTORE_DOC_LOCATION: String filePath = getCustomRestoreDocLocation(); if (!filePath.isEmpty()) { getActivity().setResult(DeveloperPreferences.RESULT_SYNC_CUSTOM); getActivity().finish(); } break; } }
Source:
<code>public static SWTBotTreeItem getTreeItem(final SWTBotTreeItem[] treeElements, final String name) { SWTBotTreeItem foundTreeItem = null; if (treeElements != null && treeElements.length > 0) { <START> for (SWTBotTreeItem swtBotTreeItem : treeElements) { <END> if (swtBotTreeItem.getText().equals(name)) { foundTreeItem = swtBotTreeItem; break; } foundTreeItem = getTreeItem(swtBotTreeItem.getItems(), name); if (foundTreeItem != null) { break; } } } return foundTreeItem; }</code><technical_language>SWTBotTreeItem.getNode(s)(String) instead of text equality test catch WidgetNotFoundException iterate recursively children items</technical_language>

Target:
public static SWTBotTreeItem getTreeItem(final SWTBotTreeItem[] treeElements, final String name) { SWTBotTreeItem foundTreeItem = null; if (treeElements != null) { for (SWTBotTreeItem swtBotTreeItem : treeElements) { if (swtBotTreeItem.getText().equals(name)) { foundTreeItem = swtBotTreeItem; break; } foundTreeItem = getTreeItem(swtBotTreeItem.getItems(), name); if (foundTreeItem != null) { break; } } } return foundTreeItem; }
Source:
<code><START> public int setCurrentSecretVersionByName(String name, long versionId) { <END> checkArgument(!name.isEmpty()); checkArgument(versionId >= 0); SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(dslContext.configuration()); Optional<SecretSeries> series = secretSeriesDAO.getSecretSeriesByName(name); if (series.isPresent()) { secretSeriesDAO.setCurrentVersion(series.get().id(), versionId); return 0; } return 1; }</code><technical_language>Instead of returning 0/1, throw exception in case of failure return type void</technical_language>

Target:
public void setCurrentSecretVersionByName(String name, long versionId) { checkArgument(!name.isEmpty()); checkArgument(versionId >= 0); SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(dslContext.configuration()); SecretSeries series = secretSeriesDAO.getSecretSeriesByName(name).orElseThrow( NotFoundException::new); secretSeriesDAO.setCurrentVersion(series.id(), versionId); }
Source:
<code>private static InsnNode simplifyArith(ArithNode arith) { if (arith.getArgsCount() != 2) { return null; } InsnArg litArg = null; InsnArg secondArg = arith.getArg(1); if (secondArg.isInsnWrap()) { InsnNode wr = ((InsnWrapArg) secondArg).getWrapInsn(); if (wr.getType() == InsnType.CONST) { litArg = wr.getArg(0); } } else if (secondArg.isLiteral()) { litArg = secondArg; } if (litArg != null) { long lit = ((LiteralArg) litArg).getLiteral(); if (arith.getOp() == ArithOp.ADD && lit < 0) { return new ArithNode(ArithOp.SUB, arith.getResult(), arith.getArg(0), InsnArg.lit(-lit, litArg.getType())); } InsnArg firstArg = arith.getArg(0); if (arith.getOp() == ArithOp.XOR && firstArg.getType() == ArgType.BOOLEAN) { <START> InsnNode node = new InsnNode(lit == 0 ? InsnType.MOVE : InsnType.NOT, 1); <END> RegisterArg result = arith.getResult(); result.setType(ArgType.BOOLEAN); node.setResult(result); node.addArg(firstArg); return node; } } return null; }</code><technical_language>Please ignore cases other lit == 0 lit == 1. I cases impossible, treat produce wrong code :)</technical_language>

Target:
private static InsnNode simplifyArith(ArithNode arith) { if (arith.getArgsCount() != 2) { return null; } InsnArg litArg = null; InsnArg secondArg = arith.getArg(1); if (secondArg.isInsnWrap()) { InsnNode wr = ((InsnWrapArg) secondArg).getWrapInsn(); if (wr.getType() == InsnType.CONST) { litArg = wr.getArg(0); } } else if (secondArg.isLiteral()) { litArg = secondArg; } if (litArg != null) { long lit = ((LiteralArg) litArg).getLiteral(); if (arith.getOp() == ArithOp.ADD && lit < 0) { return new ArithNode(ArithOp.SUB, arith.getResult(), arith.getArg(0), InsnArg.lit(-lit, litArg.getType())); } InsnArg firstArg = arith.getArg(0); if (arith.getOp() == ArithOp.XOR && firstArg.getType() == ArgType.BOOLEAN && (lit == 0 || lit == 1)) { InsnNode node = new InsnNode(lit == 0 ? InsnType.MOVE : InsnType.NOT, 1); node.setResult(arith.getResult()); node.addArg(firstArg); return node; } } return null; }
Source:
<code>public Judgment sortJudges(Judgment judgment) { <START> List<Judge> judges = judgment.getJudges().stream().collect(Collectors.toList()); <END> Collections.sort(judges, new JudgeComparator()); judgment.removeAllJudges(); judges.forEach(p -> judgment.addJudge(p)); return judgment; }</code><technical_language>judgment.getJudges().stream().collect(Collectors.toList()) replaced simple judgment.getJudges()</technical_language>

Target:
public Judgment sortJudges(Judgment judgment) { List<Judge> judges = Lists.newArrayList(judgment.getJudges()); Collections.sort(judges, new JudgeComparator()); judgment.removeAllJudges(); judges.forEach(p -> judgment.addJudge(p)); return judgment; }
Source:
<code>public boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RC_SAVE) { if (resultCode == Activity.RESULT_OK) { mResultLiveData.setValue(Resource.forVoidSuccess()); } else { Log.e(TAG, "SAVE: Canceled by user."); <START> mResultLiveData.setValue(Resource.<Void>forFailure(new Exception("Save canceled by user."))); <END> } return true; } return super.onActivityResult(requestCode, resultCode, data); }</code><technical_language>FirebaseUiException</technical_language>

Target:
public boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ResolutionCodes.RC_CRED_SAVE) { if (resultCode == Activity.RESULT_OK) { mResultLiveData.setValue(Resource.forVoidSuccess()); } else { Log.e(TAG, "SAVE: Canceled by user."); FirebaseUiException exception = new FirebaseUiException( ErrorCodes.UNKNOWN_ERROR, "Save canceled by user."); mResultLiveData.setValue(Resource.<Void>forFailure(exception)); } return true; } return super.onActivityResult(requestCode, resultCode, data); }
Source:
<code>public void bye() throws UnableToStopException { try { client.done(); client.join(); } catch (InterruptedException | IOException e) { <START> throw new UnableToStopException("Unable to stop Fit client", e); <END> } finally { testSystemStopped(null); } }</code><technical_language>Thread.currentThread.interrupt() InterruptedException</technical_language>

Target:
public void bye() throws UnableToStopException { try { client.done(); client.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new UnableToStopException("Unable to stop Fit client", e); } catch (IOException e) { throw new UnableToStopException("Unable to stop Fit client", e); } finally { testSystemStopped(null); } }
Source:
<code>private ColumnChunk readArray(GroupField field) throws IOException { List<Type> parameters = field.getType().getTypeParameters(); checkArgument(parameters.size() == 1, "Arrays must have a single type parameter, found %d", parameters.size()); Field elementField = field.getChildren().get(0).get(); ColumnChunk columnChunk = readColumnChunk(elementField); <START> IntList offsets = new IntArrayList(); <END> BooleanList valueIsNull = new BooleanArrayList(); ParquetListColumnReader.calculateCollectionOffsets(field, offsets, valueIsNull, columnChunk.getDefinitionLevels(), columnChunk.getRepetitionLevels()); Block arrayBlock = ArrayBlock.fromElementBlock(valueIsNull.size(), valueIsNull.toBooleanArray(), offsets.toIntArray(), columnChunk.getBlock()); return new ColumnChunk(arrayBlock, columnChunk.getDefinitionLevels(), columnChunk.getRepetitionLevels()); }</code><technical_language>field.getChildren().get(0) is Optional call get, is a guaranteed present in this optional? L176 do a isPresent check, (and L156)</technical_language>

Target:
private ColumnChunk readArray(GroupField field) throws IOException { List<Type> parameters = field.getType().getTypeParameters(); checkArgument(parameters.size() == 1, "Arrays must have a single type parameter, found %d", parameters.size()); Field elementField = field.getChildren().get(0).get(); ColumnChunk columnChunk = readColumnChunk(elementField); IntList offsets = new IntArrayList(); BooleanList valueIsNull = new BooleanArrayList(); calculateCollectionOffsets(field, offsets, valueIsNull, columnChunk.getDefinitionLevels(), columnChunk.getRepetitionLevels()); Block arrayBlock = ArrayBlock.fromElementBlock(valueIsNull.size(), valueIsNull.toBooleanArray(), offsets.toIntArray(), columnChunk.getBlock()); return new ColumnChunk(arrayBlock, columnChunk.getDefinitionLevels(), columnChunk.getRepetitionLevels()); }
Source:
<code>public static boolean hasWaterBottle(Player player) { if (hasAbility(player, WaterReturn.class) || isBending(player)) { return false; } PlayerInventory inventory = player.getInventory(); if (inventory.contains(Material.POTION)) { ItemStack item = inventory.getItem(inventory.first(Material.POTION)); PotionMeta meta = (PotionMeta) item.getItemMeta(); <START> return meta.getBasePotionData().getType() == PotionType.WATER); <END> } return false; }</code><technical_language>appears extra/missing parenthesis here</technical_language>

Target:
public static boolean hasWaterBottle(Player player) { if (hasAbility(player, WaterReturn.class) || isBending(player)) { return false; } PlayerInventory inventory = player.getInventory(); if (inventory.contains(Material.POTION)) { ItemStack item = inventory.getItem(inventory.first(Material.POTION)); PotionMeta meta = (PotionMeta) item.getItemMeta(); return meta.getBasePotionData().getType() == PotionType.WATER; } return false; }
Source:
<code>public static float getDensityScalar() { if (DENSITY_SCALAR == null) { <START> DENSITY_SCALAR = getDisplayMetrics().density; <END> } return DENSITY_SCALAR; }</code><technical_language>hang patch out of curiosity, lazy init this widthPixels? Is this operation expected slow</technical_language>

Target:
public static float getDensityScalar() { return getDisplayMetrics().density; }
Source:
<code>private boolean isRelevant(EntityRef entity, Vector3f position) { <START> return entity.isAlwaysRelevant() || worldProvider.isBlockRelevant(position); <END> }</code><technical_language>considered is case if any? Is more entity is relevant is more block position is relevant? If is more gain a smidgen of performance inverting expressions</technical_language>

Target:
private boolean isRelevant(EntityRef entity, Vector3f position) { return worldProvider.isBlockRelevant(position) || entity.isAlwaysRelevant(); }
Source:
<code><START> private void populateListOfDates(ArrayList<Date> dateList, Calendar populator, int totalDays) { <END> while(dateList.size() < totalDays){ dateList.add(populator.getTime()); populator.add(Calendar.DAY_OF_MONTH, 1); } int remainingDays = ((DAYSINWEEK + 1)-(populator.get(Calendar.DAY_OF_WEEK)))%DAYSINWEEK; for(int i = 0; i < remainingDays; i ++){ dateList.add(populator.getTime()); populator.add(Calendar.DAY_OF_MONTH, 1); } }</code><technical_language>This static. a good method unit tests for</technical_language>

Target:
private static void populateListOfDates(ArrayList<Date> dateList, Calendar populator, int totalDays) { while(dateList.size() < totalDays){ dateList.add(populator.getTime()); populator.add(Calendar.DAY_OF_MONTH, 1); } int remainingDays = ((DAYSINWEEK + 1)-(populator.get(Calendar.DAY_OF_WEEK)))%DAYSINWEEK; for(int i = 0; i < remainingDays; i ++){ dateList.add(populator.getTime()); populator.add(Calendar.DAY_OF_MONTH, 1); } }
Source:
<code>public Context(Object key, Object value) { <START> if (key == null) { <END> throw new IllegalArgumentException("key cannot be null."); } this.parent = null; this.key = key; this.value = value; }</code><technical_language>I replace Objects.requireNotNull fit java SDK guidelines</technical_language>

Target:
public Context(Object key, Object value) { this.parent = null; this.key = Objects.requireNonNull(key, "'key' cannot be null."); this.value = value; }
Source:
<code>void writeTo(final OutputStream out) throws IOException { writeEnum(out, getChangeType()); writeEnum(out, getPatchType()); writeString(out, oldName); writeString(out, newName); writeBytes(out, header); writeVarInt32(out, edits.size()); for (final BaseEdit e : edits) { write(out, e); <START> if (e instanceof LineEdit) { <END> List<BaseEdit> intlEdits = ((LineEdit) e).getEdits(); writeVarInt32(out, intlEdits.size()); for (BaseEdit i : intlEdits) { write(out, i); } } else { writeVarInt32(out, 0); } } }</code><technical_language>e.getEdits() != null</technical_language>

Target:
void writeTo(final OutputStream out) throws IOException { writeEnum(out, getChangeType()); writeEnum(out, getPatchType()); writeString(out, oldName); writeString(out, newName); writeBytes(out, header); writeVarInt32(out, edits.size()); for (final LineEdit e : edits) { write(out, e); if (e.getEdits() != null) { List<BaseEdit> intlEdits = e.getEdits(); writeVarInt32(out, intlEdits.size()); for (BaseEdit i : intlEdits) { write(out, i); } } else { writeVarInt32(out, 0); } } }
Source:
<code>public static void toArtifacts( Collection<org.apache.maven.artifact.Artifact> artifacts, Collection<? extends DependencyNode> nodes, List<String> trail, DependencyFilter filter ) { Map<Integer, List<org.apache.maven.artifact.Artifact>> artifactsByDepth = <START> new TreeMap<Integer, List<org.apache.maven.artifact.Artifact>>(); <END> ArrayList<org.apache.maven.artifact.Artifact> firstLevelArtifacts = new ArrayList<org.apache.maven.artifact.Artifact>( nodes.size() ); artifactsByDepth.put( 1, firstLevelArtifacts ); toArtifacts( artifactsByDepth, 1, nodes, trail, filter ); for ( List<org.apache.maven.artifact.Artifact> artifactsInDepth : artifactsByDepth.values() ) { artifacts.addAll( artifactsInDepth ); } }</code><technical_language>diamond <>. is Java 1.7 feature</technical_language>

Target:
public static void toArtifacts( Collection<org.apache.maven.artifact.Artifact> artifacts, Collection<? extends DependencyNode> nodes, List<String> trail, DependencyFilter filter ) { Map<Integer, List<org.apache.maven.artifact.Artifact>> artifactsByDepth = new TreeMap<>(); List<org.apache.maven.artifact.Artifact> firstLevelArtifacts = new ArrayList<>( nodes.size() ); artifactsByDepth.put( 1, firstLevelArtifacts ); toArtifacts( artifactsByDepth, 1, nodes, trail, filter ); for ( List<org.apache.maven.artifact.Artifact> artifactsInDepth : artifactsByDepth.values() ) { artifacts.addAll( artifactsInDepth ); } }
Source:
<code>public RelDataType deriveRowType() { if (m_program == null) { return table.getRowType(); } else { RelDataType rowDataType = m_program.getOutputRowType(); <START> if (rowDataType.getFieldCount() > 0) { <END> return rowDataType; } else { return table.getRowType(); } } }</code><technical_language>need a condition check/assert VoltDB allow for 0-column table</technical_language>

Target:
public RelDataType deriveRowType() { if (m_program == null) { return table.getRowType(); } else { RelDataType rowDataType = m_program.getOutputRowType(); if (rowDataType.getFieldCount() > 0) { return rowDataType; } else { throw new IllegalStateException("Column count can not be 0."); } } }
Source:
<code>public void showLives(int lives, int playerNumber) { livesText.setVisible(true); if (playerNumber == 1) { livesTextPlayer1.setVisible(true); if (StartController.getLimitOfPlayers() == 1) { livesTextPlayer1.setText(String.format("%d", lives)); } else { livesTextPlayer1.setText(String.format("%d (Player 1)", lives)); } } <START> if (playerNumber == 2) { <END> livesTextPlayer2.setVisible(true); livesTextPlayer2.setText(String.format("%d (Player 2)", lives)); } }</code><technical_language>else if? This is more efficient here, playerNumber 1 2 time</technical_language>

Target:
public void showLives(int lives, int playerNumber) { livesText.setVisible(true); if (playerNumber == 1) { livesTextPlayer1.setVisible(true); if (StartController.getLimitOfPlayers() == 1) { livesTextPlayer1.setText(String.format("%d", lives)); } else { livesTextPlayer1.setText(String.format("P1: %d", lives)); } } else if (playerNumber == 2) { livesTextPlayer2.setVisible(true); livesTextPlayer2.setText(String.format("P2: %d", lives)); } }
Source:
<code>public void resolvesRunningAkkaRpcActor() throws Exception { final String endpointName = "foobar"; <START> try (SimpleRpcEndpoint simpleRpcEndpoint1 = new SimpleRpcEndpoint(akkaRpcService, AkkaRpcServiceUtils.createRandomName(endpointName)); SimpleRpcEndpoint simpleRpcEndpoint2 = new SimpleRpcEndpoint(akkaRpcService, AkkaRpcServiceUtils.createRandomName(endpointName))) { <END> simpleRpcEndpoint1.closeAsync().join(); final String wildcardName = AkkaRpcServiceUtils.createWildcardName(endpointName); final String wildcardAddress = AkkaRpcServiceUtils.getLocalRpcUrl(wildcardName); final RpcGateway rpcGateway = akkaRpcService.connect(wildcardAddress, RpcGateway.class).join(); assertThat(rpcGateway.getAddress(), is(equalTo(simpleRpcEndpoint2.getAddress()))); } }</code><technical_language>suggestion try (RpcEndpoint simpleRpcEndpoint1 = createRpcEndpointWithRandomNameSuffix(endpointNamePrefix); RpcEndpoint simpleRpcEndpoint2 = createRpcEndpointWithRandomNameSuffix(endpointNamePrefix)) {</technical_language>

Target:
public void resolvesRunningAkkaRpcActor() throws Exception { final String endpointName = "foobar"; try (RpcEndpoint simpleRpcEndpoint1 = createRpcEndpointWithRandomNameSuffix(endpointName); RpcEndpoint simpleRpcEndpoint2 = createRpcEndpointWithRandomNameSuffix(endpointName)) { simpleRpcEndpoint1.closeAsync().join(); final String wildcardName = AkkaRpcServiceUtils.createWildcardName(endpointName); final String wildcardAddress = AkkaRpcServiceUtils.getLocalRpcUrl(wildcardName); final RpcGateway rpcGateway = akkaRpcService.connect(wildcardAddress, RpcGateway.class).join(); assertThat(rpcGateway.getAddress(), is(equalTo(simpleRpcEndpoint2.getAddress()))); } }
Source:
<code>public void revertCharacter(CharacterFacade character) { if (character.isDirty()) { int ret = JOptionPane.showConfirmDialog(this, LanguageBundle .getFormattedString("in_revertPcChoice", character .getNameRef().getReference()), Constants.APPLICATION_NAME, JOptionPane.YES_NO_OPTION); <START> if (ret == JOptionPane.NO_OPTION) <END> { return; } if (ret == JOptionPane.YES_OPTION) { CharacterManager.removeCharacter(character); CharacterManager.openCharacter(character.getFileRef().getReference(), PCGenFrame.this, currentDataSetRef.getReference()); } } }</code><technical_language>NO_OPTION test needed test for action</technical_language>

Target:
public void revertCharacter(CharacterFacade character) { if (character.isDirty()) { int ret = JOptionPane.showConfirmDialog(this, LanguageBundle .getFormattedString("in_revertPcChoice", character .getNameRef().getReference()), Constants.APPLICATION_NAME, JOptionPane.YES_NO_OPTION); if (ret == JOptionPane.YES_OPTION) { CharacterManager.removeCharacter(character); if (character.getFileRef().getReference() == null || StringUtils.isEmpty(character.getFileRef().getReference().getName())) { CharacterManager.openCharacter(character.getFileRef().getReference(), PCGenFrame.this, currentDataSetRef.getReference()); } else { createNewCharacter(); } } } }
Source:
<code><START> public void initModelTranslator(ModelTranslator modelTranslator) { <END> modelTranslator.registerTranslator(this.capabilityTranslator, ConsumerCapability.class, CapabilityDTO.class); }</code><technical_language>driving change increase visibility here? intended subclasses</technical_language>

Target:
protected void initModelTranslator(ModelTranslator modelTranslator) { modelTranslator.registerTranslator(this.capabilityTranslator, ConsumerCapability.class, CapabilityDTO.class); }
Source:
<code>public static void getPropertyValues(Object obj, Set<String> properties, Map<String, String> values) { try { PropertyDescriptor[] pds = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors(); int hitCount = 0; <START> hitCount = values.size(); <END> for (PropertyDescriptor pd : pds) { String propertyName = pd.getName().toLowerCase(); if (properties.contains(propertyName) && !values.containsKey(propertyName)) { Object value = null; hitCount++; try { value = pd.getReadMethod().invoke(obj); String stringValue = value != null ? value.toString() : null; values.put(propertyName, stringValue); } catch (Exception e) { log.warn("Unable to get value of property: " + pd.getDisplayName() + " for class " + obj.getClass().getName()); } if (hitCount == properties.size()) { break; } } } } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>custom values contains a values located in message, hitCount calculated in loop</technical_language>

Target:
public static void getPropertyValues(Object obj, Set<String> properties, Map<String, String> values) { try { PropertyDescriptor[] pds = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors(); int hitCount = 0; for (PropertyDescriptor pd : pds) { String propertyName = pd.getName().toLowerCase(); if (properties.contains(propertyName)) { Object value = null; hitCount++; if(!values.containsKey(propertyName)) { try { value = pd.getReadMethod().invoke(obj); String stringValue = value != null ? value.toString() : null; values.put(propertyName, stringValue); } catch (Exception e) { log.warn("Unable to get value of property: " + pd.getDisplayName() + " for class " + obj.getClass().getName()); } } if (hitCount == properties.size()) { break; } } } } catch (Exception e) { throw new RuntimeException(e); } }