auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { if (partitionsTableHandler.matches(tableName)) { return getPartitionsSystemTable(session, tableName, partitionsTableHandler.getSourceTableName(tableName)); } <START> else if (propertiesTableHandler.matches(tableName)) { <END> return getPropertiesSystemTable(session, tableName, propertiesTableHandler.getSourceTableName(tableName)); } return Optional.empty(); }</code><technical_language>Nit: else is redundant if block returns unconditionally</technical_language>

Target:
public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { if (PARTITIONS_TABLE_HANDLER.matches(tableName)) { return getPartitionsSystemTable(session, tableName, PARTITIONS_TABLE_HANDLER.getSourceTableName(tableName)); } if (PROPERTIES_TABLE_HANDLER.matches(tableName)) { return getPropertiesSystemTable(session, tableName, PROPERTIES_TABLE_HANDLER.getSourceTableName(tableName)); } return Optional.empty(); }
Source:
<code>public JAIEXTInfoImpl() { if(jaiOperations == null ){ jaiOperations = JAI_OPS; } if(jaiExtOperations == null ){ jaiExtOperations = JAIEXT_OPS; } List<OperationItem> jaiextOps = JAIExt.getJAIEXTOperations(); <START> for(OperationItem item : jaiextOps){ <END> String name = item.getName(); if (name.equalsIgnoreCase("algebric") || name.equalsIgnoreCase("operationConst") || name.equalsIgnoreCase("Stats")) { jaiExtOperations.add(name); }else if(JAIExt.isJAIAPI(name)){ jaiExtOperations.add(name); } } }</code><technical_language>This code duplicates static initializer, please factor out share</technical_language>

Target:
public JAIEXTInfoImpl() { if (jaiOperations == null) { jaiOperations = JAI_OPS; } if (jaiExtOperations == null) { jaiExtOperations = JAIEXT_OPS; } populateOperations(jaiExtOperations); }
Source:
<code>private void removeDRSnapshots() { <START> for (Guid vmId: getParameters().getSnapshotIdVmIds().keySet()) { <END> RemoveSnapshotParameters removeSnapshotParameters = new RemoveSnapshotParameters(getParameters().getSnapshotIdVmIds().get(vmId), vmId); removeSnapshotParameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); removeSnapshotParameters.setParentCommand(getActionType()); removeSnapshotParameters.setParentParameters(getParameters()); removeSnapshotParameters.setNeedsLocking(false); runInternalAction(VdcActionType.RemoveSnapshot, removeSnapshotParameters, ExecutionHandler.createInternalJobContext(getContext())); } }</code><technical_language>Consider iterate map entry, more clean: for (Map.Entry<Guid, Guid> entry : getParameters().getSnapshotIdVmIds()) { RemoveSnapshotParameters removeSnapshotParameters = new RemoveSnapshotParameters(entry.getKey(), entry.getValue())</technical_language>

Target:
private void removeDRSnapshots() { for (Map.Entry<Guid, Guid> entry : getParameters().getVmIdSnapshotIds().entrySet()) { RemoveSnapshotParameters removeSnapshotParameters = new RemoveSnapshotParameters(entry.getValue(), entry.getKey()); removeSnapshotParameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); removeSnapshotParameters.setParentCommand(getActionType()); removeSnapshotParameters.setParentParameters(getParameters()); removeSnapshotParameters.setNeedsLocking(false); runInternalAction(VdcActionType.RemoveSnapshot, removeSnapshotParameters, ExecutionHandler.createInternalJobContext(getContext())); } }
Source:
<code>public long getNumUserSessions(DbUser user) { return sessionInfoMap.keySet() .stream() .filter(sessionId -> getUser(sessionId, false).getId().equals(user.getId())) <START> .filter(sessionId -> getSessionValid(sessionId, false)) <END> .count(); }</code><technical_language>change back, work? Thanks</technical_language>

Target:
public long getNumUserSessions(DbUser user) { return sessionInfoMap.entrySet() .stream() .filter(map -> ((DbUser) map.getValue().contentOfSession.get(USER_PARAMETER_NAME)).getId() .equals(user.getId()) && getSessionValid((String) map.getValue().contentOfSession.get(ENGINE_SESSION_ID), false)) .count(); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArrayWritableObjectInspector that = (ArrayWritableObjectInspector) o; <START> if (isRoot != that.isRoot) { <END> return false; } if (typeInfo != null ? !typeInfo.equals(that.typeInfo) : that.typeInfo != null) { return false; } if (fieldInfos != null ? !fieldInfos.equals(that.fieldInfos) : that.fieldInfos != null) { return false; } if (fieldNames != null ? !fieldNames.equals(that.fieldNames) : that.fieldNames != null) { return false; } if (fields != null ? !fields.equals(that.fields) : that.fields != null) { return false; } return fieldsByName != null ? fieldsByName.equals(that.fieldsByName) : that.fieldsByName == null; }</code><technical_language>hint: merge "if" clauses? equals method. break lines "||" for view</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArrayWritableObjectInspector that = (ArrayWritableObjectInspector) o; if (isRoot != that.isRoot || (typeInfo != null ? !typeInfo.equals(that.typeInfo) : that.typeInfo != null) || (fieldInfos != null ? !fieldInfos.equals(that.fieldInfos) : that.fieldInfos != null) || (fieldNames != null ? !fieldNames.equals(that.fieldNames) : that.fieldNames != null) || (fields != null ? !fields.equals(that.fields) : that.fields != null)) { return false; } return fieldsByName != null ? fieldsByName.equals(that.fieldsByName) : that.fieldsByName == null; }
Source:
<code>public String getTasksWithNoParent() throws SQLException { <START> ArrayList<TaskObject> existedTask = mProductBacklogHelper.getTasksWithNoParent(); <END> Gson gson = new Gson(); return gson.toJson(existedTask); }</code><technical_language>existingTasks</technical_language>

Target:
public String getTasksWithNoParent() throws SQLException { ArrayList<TaskObject> existingTasks = mProductBacklogHelper.getTasksWithNoParent(); Gson gson = new Gson(); return gson.toJson(existingTasks); }
Source:
<code>public void process() { if (material == null) { shaderManager.disableShader(); <START> } else { <END> material.enable(); } }</code><technical_language>Hmmm. process() method lean possible. This calls for a DisableMaterial() class default instance, in process method is shaderManager.disableShader();</technical_language>

Target:
public void process() { material.enable(); }
Source:
<code>private boolean defaultAutodiscoverRedirectionUrlValidationCallback( String redirectionUrl) throws AutodiscoverLocalException { throw new AutodiscoverLocalException(String.format( <START> "Autodiscover blocked a potentially insecure redirection to %s. To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload.", redirectionUrl)); <END> }</code><technical_language>is this correct line-lenght</technical_language>

Target:
private boolean defaultAutodiscoverRedirectionUrlValidationCallback( String redirectionUrl) throws AutodiscoverLocalException { throw new AutodiscoverLocalException(String.format( "Autodiscover blocked a potentially insecure redirection to %s. To allow Autodiscover to follow the " + "redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) " + "overload.", redirectionUrl)); }
Source:
<code>public void resolveMessageShouldResolveMessageWhenMessageKeyExists() { <START> messageSource.addMessage(BIRTHDAY_MESSAGE_KEY, dummyLocale, BIRTHDAY_MESSAGE); <END> String message = messageKeyResolver.resolveMessage(BIRTHDAY_MESSAGE_KEY); assertThat(message, equalTo(BIRTHDAY_MESSAGE)); }</code><technical_language>in setUp(). more realistic messages defined, choose them, compared message in messageSource</technical_language>

Target:
public void resolveMessageShouldResolveMessageWhenMessageKeyExists() throws MessageResolutionFailedException { String message = messageKeyResolver.resolveMessage(EXAMPLE_MESSAGE_KEY); assertThat(message, equalTo(EXAMPLE_MESSAGE)); }
Source:
<code>private static <T> T getResponseContent(DefaultHttpClient client, HttpUriRequest request, HttpContext context, String message, Class<T> clz, boolean isReturnServerError) throws XtentisException { if (null == request) { throw new IllegalArgumentException("null request"); } HttpResponse response = null; try { response = client.execute(request, context); StatusLine statusLine = response.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == 501) { throw new OperationIgnoredException(Messages.HttpClientUtil_Error_501); } return wrapResponse(response, message, clz, isReturnServerError); } catch (OperationIgnoredException ex) { throw ex; } catch (InternalServerErrorException ex) { throw ex; } catch (XtentisException ex) { throw ex; } catch (Exception e) { LOG.error(e.getMessage(), e); <START> request.abort(); <END> throw new XtentisException(e.getMessage(), e); } finally { closeResponse(response); } }</code><technical_language>wrap "request.abort()" **try** avoid throw exception</technical_language>

Target:
private static <T> T getResponseContent(DefaultHttpClient client, HttpUriRequest request, HttpContext context, String message, Class<T> clz, boolean isReturnServerError) throws XtentisException { if (null == request) { throw new IllegalArgumentException("null request"); } HttpResponse response = null; try { response = client.execute(request, context); StatusLine statusLine = response.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == 501) { throw new OperationIgnoredException(Messages.HttpClientUtil_Error_501); } return wrapResponse(response, message, clz, isReturnServerError); } catch (OperationIgnoredException ex) { throw ex; } catch (InternalServerErrorException ex) { throw ex; } catch (XtentisException ex) { throw ex; } catch (Exception e) { LOG.error(e.getMessage(), e); try { request.abort(); } catch (Exception e1) { } throw new XtentisException(e.getMessage(), e); } finally { closeResponse(response); } }
Source:
<code>public static void cacheRealmWithEverything(KeycloakSession session, String realmName) { RealmModel realm = session.realms().getRealmByName(realmName); for (ClientModel client : realm.getClients()) { realm.getClientById(client.getId()); realm.getClientByClientId(client.getClientId()); cacheRoles(session, realm, client); } cacheRoles(session, realm, realm); for (GroupModel group : realm.getTopLevelGroups()) { cacheGroupRecursive(realm, group); } <START> for (ClientScopeModel clientTemplate : realm.getClientScopes()) { <END> realm.getClientScopeById(clientTemplate.getId()); } for (UserModel user : session.users().getUsers(realm)) { session.users().getUserById(user.getId(), realm); if (user.getEmail() != null) { session.users().getUserByEmail(user.getEmail(), realm); } session.users().getUserByUsername(user.getUsername(), realm); session.users().getConsents(realm, user.getId()); for (FederatedIdentityModel fedIdentity : session.users().getFederatedIdentities(user, realm)) { session.users().getUserByFederatedIdentity(fedIdentity, realm); } } }</code><technical_language>clientScope</technical_language>

Target:
public static void cacheRealmWithEverything(KeycloakSession session, String realmName) { RealmModel realm = session.realms().getRealmByName(realmName); for (ClientModel client : realm.getClients()) { realm.getClientById(client.getId()); realm.getClientByClientId(client.getClientId()); cacheRoles(session, realm, client); } cacheRoles(session, realm, realm); for (GroupModel group : realm.getTopLevelGroups()) { cacheGroupRecursive(realm, group); } for (ClientScopeModel clientScope : realm.getClientScopes()) { realm.getClientScopeById(clientScope.getId()); } for (UserModel user : session.users().getUsers(realm)) { session.users().getUserById(user.getId(), realm); if (user.getEmail() != null) { session.users().getUserByEmail(user.getEmail(), realm); } session.users().getUserByUsername(user.getUsername(), realm); session.users().getConsents(realm, user.getId()); for (FederatedIdentityModel fedIdentity : session.users().getFederatedIdentities(user, realm)) { session.users().getUserByFederatedIdentity(fedIdentity, realm); } } }
Source:
<code>public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ModelNode operationModel = new ModelNode(); populateModel(operation, operationModel); String attributeName = NAME.resolveModelAttribute(context, operationModel).asString(); AttributeAccess attributeAccess = context.getResourceRegistration().getAttributeAccess(PathAddress.EMPTY_ADDRESS, attributeName); if (attributeAccess == null) { throw new OperationFailedException(new ModelNode().set(ControllerLogger.ROOT_LOGGER.unknownAttribute(attributeName))); } else if (requiredReadWriteAccess && attributeAccess.getAccessType() != AttributeAccess.AccessType.READ_WRITE) { throw new OperationFailedException(new ModelNode().set(ControllerLogger.ROOT_LOGGER.attributeNotWritable(attributeName))); } Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS); ModelNode model = resource.getModel().get(attributeName); <START> updateModel(context, operationModel, attributeAccess.getAttributeDefinition(), model); <END> if (requiredReadWriteAccess) { final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)); ModelNode writeOperation = Util.createOperation(WriteAttributeHandler.DEFINITION, address); writeOperation.get(NAME.getName()).set(attributeName); writeOperation.get(ModelDescriptionConstants.VALUE).set(model); context.addStep(writeOperation, WriteAttributeHandler.INSTANCE, OperationContext.Stage.MODEL); } context.stepCompleted(); }</code><technical_language>This is argument #199. a ref read-only model intent modify it. Safer is clone first, argument PR</technical_language>

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ModelNode operationModel = new ModelNode(); populateModel(operation, operationModel); final String attributeName = NAME.resolveModelAttribute(context, operationModel).asString(); final AttributeAccess attributeAccess = context.getResourceRegistration().getAttributeAccess(PathAddress.EMPTY_ADDRESS, attributeName); if (attributeAccess == null) { throw new OperationFailedException(new ModelNode().set(ControllerLogger.ROOT_LOGGER.unknownAttribute(attributeName))); } else if (requiredReadWriteAccess && attributeAccess.getAccessType() != AttributeAccess.AccessType.READ_WRITE) { throw new OperationFailedException(new ModelNode().set(ControllerLogger.ROOT_LOGGER.attributeNotWritable(attributeName))); } final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)); Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS); ModelNode model = resource.getModel().get(attributeName); updateModel(context, operationModel, attributeAccess.getAttributeDefinition(), model); if (requiredReadWriteAccess) { ModelNode writeOperation = Util.createOperation(WriteAttributeHandler.DEFINITION, address); writeOperation.get(NAME.getName()).set(attributeName); writeOperation.get(ModelDescriptionConstants.VALUE).set(model); context.addStep(writeOperation, WriteAttributeHandler.INSTANCE, OperationContext.Stage.MODEL); } context.stepCompleted(); }
Source:
<code>public void testRepeat() { { Assert.assertEquals("", StringUtils.repeat("foo", 0)); Assert.assertEquals("foo", StringUtils.repeat("foo", 1)); Assert.assertEquals("foofoofoo", StringUtils.repeat("foo", 3)); <START> } <END> { Assert.assertEquals("", StringUtils.repeat("", 0)); Assert.assertEquals("", StringUtils.repeat("", 1)); Assert.assertEquals("", StringUtils.repeat("", 3)); } { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("count is negative, -1"); Assert.assertEquals("", StringUtils.repeat("foo", -1)); } }</code><technical_language>nit: replace } a blank line? is code style in druid. for { } below</technical_language>

Target:
public void testRepeat() { Assert.assertEquals("", StringUtils.repeat("foo", 0)); Assert.assertEquals("foo", StringUtils.repeat("foo", 1)); Assert.assertEquals("foofoofoo", StringUtils.repeat("foo", 3)); Assert.assertEquals("", StringUtils.repeat("", 0)); Assert.assertEquals("", StringUtils.repeat("", 1)); Assert.assertEquals("", StringUtils.repeat("", 3)); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("count is negative, -1"); Assert.assertEquals("", StringUtils.repeat("foo", -1)); }
Source:
<code>protected Content(Content source) { this.setUuid(source.getUuid()); this.setId(source.getId()); <START> this.setCreated(source.getCreated()); <END> this.setUpdated(source.getUpdated()); this.setType(source.getType()); this.setLabel(source.getLabel()); this.setOwners(source.getOwners()); this.setName(source.getName()); this.setVendor(source.getVendor()); this.setContentUrl(source.getContentUrl()); this.setRequiredTags(source.getRequiredTags()); this.setReleaseVer(source.getReleaseVer()); this.setGpgUrl(source.getGpgUrl()); this.setMetadataExpire(source.getMetadataExpire()); this.setModifiedProductIds(source.getModifiedProductIds()); this.setArches(source.getArches()); }</code><technical_language>Date is immutable in Java, this create a problem objects referencing Date object? a defensive copy here? setCreated(new Date(source.getCreated().getTime()))</technical_language>

Target:
protected Content(Content source) { this.setUuid(source.getUuid()); this.setId(source.getId()); this.setCreated(source.getCreated() != null ? (Date) source.getCreated().clone() : null); this.setUpdated(source.getUpdated() != null ? (Date) source.getUpdated().clone() : null); this.setType(source.getType()); this.setLabel(source.getLabel()); this.setOwners(source.getOwners()); this.setName(source.getName()); this.setVendor(source.getVendor()); this.setContentUrl(source.getContentUrl()); this.setRequiredTags(source.getRequiredTags()); this.setReleaseVer(source.getReleaseVer()); this.setGpgUrl(source.getGpgUrl()); this.setMetadataExpire(source.getMetadataExpire()); this.setArches(source.getArches()); this.setModifiedProductIds(source.getModifiedProductIds() != null ? new HashSet<String>(source.getModifiedProductIds()) : null); }
Source:
<code>public static void main(String[] args) { <START> System.setProperty("spring.jpa.hibernate.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy"); <END> SpringApplication.run(ResourceServer.class, args); }</code><technical_language>Thanks for notice. a look</technical_language>

Target:
public static void main(String[] args) { SpringApplication application = new SpringApplication(ResourceServer.class, args); application.setDefaultProperties(NAMING_STRATEGY); application.run(); }
Source:
<code>public TaskRepository repository() { if (repository != null) { return repository; } repository = new TaskRepository(getConnectorKind(), getRepositoryUrl()); UserCredentials credentials = CommonTestUtil.getCredentials(PrivilegeLevel.USER); <START> if (Boolean.parseBoolean(getProperty("api_key_enabled"))) { <END> repository.setProperty(IBugzillaRestConstants.REPOSITORY_USE_API_KEY, Boolean.toString(true)); repository.setProperty(IBugzillaRestConstants.REPOSITORY_API_KEY, userAPIKeyMap.getOrDefault(credentials.getUserName(), "")); repository.setCredentials(org.eclipse.mylyn.commons.net.AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), ""), false); } else { repository.setCredentials(org.eclipse.mylyn.commons.net.AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), credentials.getPassword()), true); } return repository; }</code><technical_language>I a public constant for this this class</technical_language>

Target:
public TaskRepository repository() { if (repository != null) { return repository; } repository = new TaskRepository(getConnectorKind(), getRepositoryUrl()); UserCredentials credentials = CommonTestUtil.getCredentials(PrivilegeLevel.USER); if (Boolean.parseBoolean(getProperty(IBugzillaRestConstants.API_KEY_ENABLED_PROPERTY))) { repository.setProperty(IBugzillaRestConstants.REPOSITORY_USE_API_KEY, Boolean.toString(true)); repository.setProperty(IBugzillaRestConstants.REPOSITORY_API_KEY, userAPIKeyMap.getOrDefault(credentials.getUserName(), "")); repository.setCredentials(org.eclipse.mylyn.commons.net.AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), ""), false); } else { repository.setCredentials(org.eclipse.mylyn.commons.net.AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), credentials.getPassword()), true); } return repository; }
Source:
<code>public GraphDatabaseService create() { LOG.infof( "1. Try create new service instance for dbPath %s", dbLocation ); final String dbLocationAbsolutePath = dbLocation.getAbsolutePath(); LOG.infof( "2. Try create new service instance for dbPath %s", dbLocationAbsolutePath ); return GRAPH_DATABASE_SERVICE_MAP.computeIfAbsent( dbLocationAbsolutePath, ( String path ) -> { LOG.infof( " Create new service instance for dbPath %s", dbLocationAbsolutePath ); <START> return buildGraphDatabaseService(); <END> } ); }</code><technical_language>do need log 3 times? print absolutePath? I prefer add a lot of redundant information in output of log,</technical_language>

Target:
public GraphDatabaseService create() { LOG.infof( "1. Try create new service instance for dbPath %s", dbLocation ); final String dbLocationAbsolutePath = dbLocation.getAbsolutePath(); LOG.infof( "2. Try create new service instance for dbPath %s", dbLocationAbsolutePath ); if ( !GRAPH_DATABASE_SERVICE_MAP.containsKey( dbLocationAbsolutePath ) ) { synchronized (GRAPH_DATABASE_SERVICE_MAP) { if ( !GRAPH_DATABASE_SERVICE_MAP.containsKey( dbLocationAbsolutePath ) ) { LOG.infof( " Create new service instance for dbPath %s", dbLocationAbsolutePath ); GraphDatabaseService service = buildGraphDatabaseService(); LOG.infof( " Create dnew service %s instance for dbPath %s",service, dbLocationAbsolutePath ); GRAPH_DATABASE_SERVICE_MAP.put( dbLocationAbsolutePath, service ); } } } return GRAPH_DATABASE_SERVICE_MAP.get( dbLocationAbsolutePath ); }
Source:
<code>private void initTitleActions() { List<Action> tools = new ArrayList<Action>(); saveAction = new DefaultAction("SAVE_MAP", I18N.tr("Save"), I18N.tr("Save the Map"), OrbisGISIcon.getIcon("save"), EventHandler.create(ActionListener.class, this, "onSaveMapContext"), KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); saveAction.setEnabled(false); tools.add(saveAction); <START> DefaultAction addWMSAction = new DefaultAction("ADD_WMS_LAYER", I18N.tr("Add"), <END> I18N.tr("Add WMS layer"), OrbisGISIcon.getIcon("add"), EventHandler.create(ActionListener.class, this, "onAddWMSLayer"), KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); tools.add(addWMSAction); dockingPanelParameters.setDockActions(tools); }</code><technical_language>I18N.tr("Add WMS layer")</technical_language>

Target:
private void initTitleActions() { List<Action> tools = new ArrayList<Action>(); saveAction = new DefaultAction("SAVE_MAP", I18N.tr("Save"), I18N.tr("Save the Map"), OrbisGISIcon.getIcon("save"), EventHandler.create(ActionListener.class, this, "onSaveMapContext"), KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); saveAction.setEnabled(false); tools.add(saveAction); DefaultAction addWMSAction = new DefaultAction("ADD_WMS_LAYER", I18N.tr("WMS layer"), I18N.tr("Add WMS layer"), OrbisGISIcon.getIcon("add"), EventHandler.create(ActionListener.class, this, "onAddWMSLayer"), KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); tools.add(addWMSAction); dockingPanelParameters.setDockActions(tools); }
Source:
<code>private static void doLoadScenarioExecution(final JaasEnvApiClient.JaasResponse jaasResponse, final URL directory) { JaasExecApiClient execApiClient = null; try { execApiClient = new JaasExecApiClient(jaasResponse.getExecutionId(), environmentProperties.getProperty("realtime.jaas.endpoint") ); Optional<TestExecutionEntity> optionalExecution = execApiClient.getExecution(); if (!optionalExecution.isPresent()) { return; } TestExecutionEntity execution = optionalExecution.get(); if (execution.getStatus() != TestExecutionEntity.TestExecutionStatus.PENDING) { <START> log.warn("Received execution is not in PENDING state. Going to proceed with next..."); <END> return; } execApiClient.startExecution(); String sessionId = null; if (execution.getTestProjectURL() == null) { environmentProperties.setProperty(LOAD_SCENARIO_ID_PROP, execution.getLoadScenarioId()); System.setProperty(USER_CONFIGS_PACKAGE, environmentProperties.getProperty(USER_CONFIGS_PACKAGE)); sessionId = doLaunchMaster(directory); } else { sessionId = executeDynamicLoadScenario(execution.getLoadScenarioId(), execution.getTestProjectURL(), directory); } execApiClient.completeExecution(sessionId); } catch (Exception e) { log.error("Error during a load scenario execution", e); if (execApiClient != null) { execApiClient.failExecution(ExceptionUtils.getMessage(e) + " With root cause message: " + ExceptionUtils .getRootCauseMessage(e)); } } }</code><technical_language>Received execution id is not..</technical_language>

Target:
private static void doLoadScenarioExecution(final JaasEnvApiClient.JaasResponse jaasResponse, final URL directory) { JaasExecApiClient execApiClient = null; try { execApiClient = new JaasExecApiClient(jaasResponse.getExecutionId(), environmentProperties.getProperty("realtime.jaas.endpoint") ); Optional<TestExecutionEntity> optionalExecution = execApiClient.getExecution(); if (!optionalExecution.isPresent()) { return; } TestExecutionEntity execution = optionalExecution.get(); if (execution.getStatus() != TestExecutionEntity.TestExecutionStatus.PENDING) { log.warn("Received execution with id '{}' is not in PENDING state. Going to proceed with next...", execution.getId()); return; } execApiClient.startExecution(); String sessionId = null; if (execution.getTestProjectURL() == null) { environmentProperties.setProperty(LOAD_SCENARIO_ID_PROP, execution.getLoadScenarioId()); System.setProperty(USER_CONFIGS_PACKAGE, environmentProperties.getProperty(USER_CONFIGS_PACKAGE)); sessionId = doLaunchMaster(directory); } else { sessionId = executeDynamicLoadScenario(execution.getLoadScenarioId(), execution.getTestProjectURL(), directory); } execApiClient.completeExecution(sessionId); } catch (Exception e) { log.error("Error during a load scenario execution", e); if (execApiClient != null) { execApiClient.failExecution(ExceptionUtils.getMessage(e) + " With root cause message: " + ExceptionUtils .getRootCauseMessage(e)); } } }
Source:
<code>public final void startDatabase() { if (!databaseStarted) { synchronized (this) { if (!databaseStarted) { <START> LOG.debug("Starting a connection to the database"); <END> onStartDatabase(); } } } }</code><technical_language>Period end of log statement</technical_language>

Target:
public final void startDatabase() { if (!databaseStarted) { synchronized (this) { if (!databaseStarted) { LOG.debug("Starting a connection to the database."); onStartDatabase(); } } } }
Source:
<code>static Optional<ImmutablePair<String, String>> findSupportedTargetPath(List<ProvisionInterface> pluginList, List<String> targetPaths) { for (String target : targetPaths) { URI objectIdentifier = URI.create(target); String scheme = objectIdentifier.getScheme().toLowerCase(); <START> if (scheme != null) { <END> for (ProvisionInterface provisionInterface : pluginList) { if (StringUtils.containsIgnoreCase(provisionInterface.schemesHandled().iterator().next(), scheme)) { return Optional.of(new ImmutablePair<>(target, scheme)); } } } } return Optional.empty(); }</code><technical_language>variable scheme null. If objectIdentifier.getScheme() returns null, if possible, get a null pointer exception toLowerCase() this code execute. If return null, toLowerCase() return null. check if objectIdentifier.getScheme returns null</technical_language>

Target:
static Optional<ImmutablePair<String, String>> findSupportedTargetPath(List<ProvisionInterface> pluginList, List<String> targetPaths) { for (String target : targetPaths) { try { URI objectIdentifier = URI.create(target); String scheme = (objectIdentifier.getScheme() != null) ? objectIdentifier.getScheme().toLowerCase() : null; if (scheme != null) { for (ProvisionInterface provisionInterface : pluginList) { for (String currentScheme : provisionInterface.schemesHandled()) { if (StringUtils.containsIgnoreCase(currentScheme, scheme)) { return Optional.of(new ImmutablePair<>(target, scheme)); } } } } } catch (IllegalArgumentException e) { LOG.info("Bad target"); } } return Optional.empty(); }
Source:
<code>public static BlobProperties deserializeBlobProperties(CrcInputStream crcStream) throws IOException, DataCorruptException { try { DataInputStream dataStream = new DataInputStream(crcStream); SystemMetadataType type = SystemMetadataType.values()[dataStream.readShort()]; if (type != SystemMetadataType.BlobPropertyRecord) <START> throw new IllegalArgumentException("Invalid system metadata type"); <END> BlobProperties properties = BlobPropertySerDe.getBlobPropertyFromStream(dataStream); long crc = crcStream.getValue(); if (crc != dataStream.readLong()) { logger.error("corrupt data while parsing blob properties"); throw new DataCorruptException("Blob property data is corrupt"); } return properties; } catch (Exception e) { logger.error("Blob property failed to be parsed. Data may be corrupt with exception {}", e); throw new DataCorruptException("Blob property failed to be parsed. Data may be corrupt"); } }</code><technical_language>usages of IllegalArgumentException DataCorruptExchange sense me. stated before, imagine "InvalidDataException" in lieu of IllegalArgumentException here. I dislike re-use of "DataCorruptException" in catch (Exception e) clause. prefer a more vague "DeserializationException" some such. caught exception in construction of re-thrown exception cause-chain is clear. Actually, comparing deserializeBlobProperties deserializeDeleteRecord, exception pattern is differnt. deserializeBlobProperties outer try/catch re-throw unnecessary converts exceptions (re)thrown DataCorruptExceptions. I logger.error messaging (re)throwing. of making this automagic? I dislike distinct strings in this code, for logger for exception prefer a single string. I of clean of mkaing this a liner though. Adding a logException method class logs error throws is awkward. Adding logger exception's constructor awkward. code review for consistent usage. decide a pattern for logging (re)throwing exceptions, need consistently</technical_language>

Target:
public static BlobProperties deserializeBlobProperties(CrcInputStream crcStream) throws IOException, DataCorruptException { try { DataInputStream dataStream = new DataInputStream(crcStream); SystemMetadataRecordType type = SystemMetadataRecordType.values()[dataStream.readShort()]; if (type != SystemMetadataRecordType.BlobPropertyRecord) throw new IllegalArgumentException("Invalid system metadata type"); BlobProperties properties = BlobPropertySerDe.getBlobPropertyFromStream(dataStream); long crc = crcStream.getValue(); if (crc != dataStream.readLong()) { logger.error("corrupt data while parsing blob properties"); throw new DataCorruptException("Blob property data is corrupt"); } return properties; } catch (Exception e) { logger.error("Blob property failed to be parsed. Data may be corrupt with exception {}", e); throw new DataCorruptException("Blob property failed to be parsed. Data may be corrupt"); } }
Source:
<code>private void handleMenuElementRemove(MenuManager manager, Iterable<MMenuElement> menuElements) { Iterator<MMenuElement> iterMenuElements = menuElements.iterator(); if (!iterMenuElements.hasNext()) return; while (iterMenuElements.hasNext()) { MMenuElement menuElement = iterMenuElements.next(); if (menuElement instanceof MMenu) { MMenu menuModel = (MMenu) menuElement; MenuManager mi = getManager(menuModel); <START> manager.remove(mi); <END> clearModelToManager(menuModel, mi); handleMenuElementRemove(mi, menuModel.getChildren()); mi.dispose(); } else { IContributionItem ci = getContribution(menuElement); manager.remove(ci); clearModelToContribution(menuElement, ci); ci.dispose(); } } if (!disposingMenuUIElement) { manager.updateAll(false); } }</code><technical_language>mi null, some NPE's there. NPE check added: if (mi == null) { continue; }</technical_language>

Target:
private void handleMenuElementRemove(MenuManager manager, Iterable<MMenuElement> menuElements) { Iterator<MMenuElement> iterMenuElements = menuElements.iterator(); if (!iterMenuElements.hasNext()) return; while (iterMenuElements.hasNext()) { MMenuElement menuElement = iterMenuElements.next(); if (menuElement instanceof MMenu) { MMenu menuModel = (MMenu) menuElement; MenuManager mi = getManager(menuModel); if (mi == null) { continue; } manager.remove(mi); clearModelToManager(menuModel, mi); handleMenuElementRemove(mi, menuModel.getChildren()); mi.dispose(); } else { IContributionItem ci = getContribution(menuElement); if (ci == null) { continue; } manager.remove(ci); clearModelToContribution(menuElement, ci); ci.dispose(); } } if (!disposingMenuUIElement) { manager.updateAll(false); } }
Source:
<code>public void testRestartWithKarafRestart() throws Exception { final ApplicationServiceBean serviceBean = new ApplicationServiceBean( testAppService, testConfigAdminExt, mBeanServer, mockFeaturesService, mockSystemService); serviceBean.restart(); assertThat( <START> "Restart system property was cleared", System.getProperty(RESTART_JVM), equalTo("false")); <END> assertThat(ddfBin.resolve("restart.jvm").toFile().exists(), equalTo(true)); verify(mockSystemService).halt(); verify(mockWrapperManager, Mockito.never()).restart(); }</code><technical_language>a bit confused asserting karaf.restart.jvm is set false test name restarting Karaf Restart. misinterpreting purpose of this test. testing Karaf restart service is reused name sounds</technical_language>

Target:
public void testRestartWithKarafRestart() throws Exception { final ApplicationServiceBean serviceBean = newApplicationServiceBean(); serviceBean.restart(); assertThat( "Restart system property was cleared", System.getProperty(RESTART_JVM), equalTo("false")); assertThat(ddfBin.resolve("restart.jvm").toFile(), FileMatchers.anExistingFile()); verify(mockSystemService).halt(); verify(mockWrapperManager, Mockito.never()).restart(); }
Source:
<code>public AddPartitionsToTxnResponse getErrorResponse(int throttleTimeMs, Throwable e) { final HashMap<TopicPartition, Errors> errors = new HashMap<>(); <START> for (TopicPartition partition : Builder.getPartitions(data)) { <END> errors.put(partition, Errors.forException(e)); } return new AddPartitionsToTxnResponse(throttleTimeMs, errors); }</code><technical_language>here, cache result of Builder.getPartitions(data) for re-use</technical_language>

Target:
public AddPartitionsToTxnResponse getErrorResponse(int throttleTimeMs, Throwable e) { final HashMap<TopicPartition, Errors> errors = new HashMap<>(); for (TopicPartition partition : partitions()) { errors.put(partition, Errors.forException(e)); } return new AddPartitionsToTxnResponse(throttleTimeMs, errors); }
Source:
<code>protected void sendDmxData() { long now = System.currentTimeMillis(); universe.calculateBuffer(now); for (IpNode receiverNode : receiverNodes.keySet()) { <START> Socket socket = receiverNodes.get(receiverNode); <END> if (socket.isConnected()) { try { socket.getOutputStream().write(universe.getBuffer()); } catch (IOException e) { logger.warn("Could not send to in {}: {}", receiverNode, this.thing.getUID(), e); isConnected = false; return; } } else { isConnected = false; return; } } }</code><technical_language>This method in OlaBridgeHandler. class DmxBridgeHandler methods anyway, implementing core of this method a parameter if need specific</technical_language>

Target:
protected void sendDmxData() { if (this.thing.getStatus().equals(ThingStatus.ONLINE)) { long now = System.currentTimeMillis(); universe.calculateBuffer(now); for (IpNode receiverNode : receiverNodes.keySet()) { Socket socket = receiverNodes.get(receiverNode); if (socket.isConnected()) { try { socket.getOutputStream().write(universe.getBuffer()); } catch (IOException e) { logger.debug("Could not send to in {}: {}", receiverNode, this.thing.getUID(), e); closeConnection(ThingStatusDetail.COMMUNICATION_ERROR, "could not send DMX data"); return; } } else { closeConnection(ThingStatusDetail.NONE, "reconnect"); return; } } } else { openConnection(); } }
Source:
<code>DiskSpaceRequirements getDiskSpaceRequirements() throws StoreException { synchronized (lock) { checkStarted(); <START> DiskSpaceRequirements requirements = log.getDiskSpaceRequirements(); <END> if (requirements != null) { requirements = new DiskSpaceRequirements(requirements.getSegmentSizeInBytes(), requirements.getSegmentsNeeded(), requirements.getSwapSegmentsInUse() + compactor.getSwapSegmentsInUse()); } return requirements; } }</code><technical_language>recommend exposing a method in log get unallocated segments count. generate new DiskSpaceRequirements(log.getSegmentCapacity(), log.getUnAllocatedSegmentsCount(), compactor.getSwapSegmentsInUse()). This a notion log some swap segments compaction</technical_language>

Target:
DiskSpaceRequirements getDiskSpaceRequirements() throws StoreException { checkStarted(); DiskSpaceRequirements requirements = log.isLogSegmented() ? new DiskSpaceRequirements(log.getSegmentCapacity(), log.getRemainingUnallocatedSegments(), compactor.getSwapSegmentsInUse()) : null; logger.debug("Store has disk space requirements: {}", storeId, requirements); return requirements; }
Source:
<code>public String executeCommand() { String cliOutput = ""; ByteArrayOutputStream out = new ConstraintByteArrayOutputStream(500); String command = Config.<String> GetValue(ConfigValues.GlusterPeerStatusCommand); try { client.executeCommand(command, null, out, null); cliOutput = new String(out.toByteArray(), "UTF-8"); } catch (Exception e) { String m = String.format("SSH error running command %1$s '%2$s': %3$s", this.host, command, e.getMessage()); log.error(m, e); } <START> return cliOutput; <END> }</code><technical_language>exception in case of error</technical_language>

Target:
protected String executeCommand() { String cliOutput = ""; ByteArrayOutputStream out = new ConstraintByteArrayOutputStream(500); String command = Config.<String> GetValue(ConfigValues.GlusterPeerStatusCommand); client.setUser("root"); client.setPassword(getParameters().getRootPassword()); try { client.authenticate(); client.executeCommand(command, null, out, null); cliOutput = new String(out.toByteArray(), "UTF-8"); } catch (Exception e) { String m = String.format("SSH error running command %1$s '%2$s': %3$s", this.host, command, e.getMessage()); log.error(m, e); throw new RuntimeException(e); } return cliOutput; }
Source:
<code>public String getAuthorizationUrl(OAuthConfig config) { <START> System.out.print("Authorisation URL: "); <END> String url = String.format(AUTHORIZE_URL, OAuthEncoder.encode(config.getApiKey()), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()), OAuthEncoder.encode(config.getState())); return url; }</code><technical_language>forgotten line of code</technical_language>

Target:
public String getAuthorizationUrl(OAuthConfig config) { String url = String.format(AUTHORIZE_URL, OAuthEncoder.encode(config.getApiKey()), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()), OAuthEncoder.encode(config.getState())); return url; }
Source:
<code><START> public void doGet(final HttpServletRequest req, <END> final HttpServletResponse rsp) throws IOException { serve(req, rsp, true); }</code><technical_language>This a recurring pattern. pull abstract parent subclasses handle serve(req,res,true/false)</technical_language>

Target:
public void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { nocache(rsp); sendPlainText(packList(req), req, rsp); }
Source:
<code>private static boolean validateWildcard(MetaClass bindable) { <START> if(bindable.isFinal()) { <END> log.info("@Bindable types cannot be final, ignoring: " + bindable.getFullyQualifiedName()); return false; } return true; }</code><technical_language>Please fix formatting is space if parenthesis</technical_language>

Target:
private static boolean validateWildcard(MetaClass bindable) { if (bindable.isFinal()) { log.debug("@Bindable types cannot be final, ignoring: {}", bindable.getFullyQualifiedName()); return false; } return true; }
Source:
<code>public String getNewBtcAddress() { try { BitcoinCli newAddress = new BitcoinCli(config, "getnewaddress").run(); if (newAddress.isError()) <START> fail(format("Could generate new bitcoin address:%n%s", newAddress.getErrorMessage())); <END> return newAddress.getOutput(); } catch (IOException | InterruptedException ex) { fail(ex); return null; } }</code><technical_language>Typo? "Could _not_ generate ..."</technical_language>

Target:
public String getNewBtcAddress() { try { BitcoinCli newAddress = new BitcoinCli(config, "getnewaddress").run(); if (newAddress.isError()) fail(format("Could not generate new bitcoin address:%n%s", newAddress.getErrorMessage())); return newAddress.getOutput(); } catch (IOException | InterruptedException ex) { fail(ex); return null; } }
Source:
<code>boolean areAllContainersRunning(Pod pod) { <START> return pod.getSpec().getContainers().size() == pod.getStatus().getContainerStatuses().size() && !PodUtils.getContainerStatus(pod).stream().anyMatch(cs -> !cs.getReady()); <END> }</code><technical_language>suggestion return pod.getSpec().getContainers().size() == pod.getStatus().getContainerStatuses().size() && PodUtils.getContainerStatus(pod).stream().allMatch(ContainerStatus::getReady);</technical_language>

Target:
boolean areAllContainersRunning(Pod pod) { return pod.getSpec().getContainers().size() == pod.getStatus().getContainerStatuses().size() && PodUtils.getContainerStatus(pod).stream().allMatch(ContainerStatus::getReady); }
Source:
<code>private void saveImageToMediaStore() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGallerySave(pageTitle, galleryItem.getName()); <START> final Bitmap savedImageBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); <END> new SaneAsyncTask<String>(SaneAsyncTask.SINGLE_THREAD) { @Override public String performTask() throws Throwable { String localUrl = MediaStore.Images.Media.insertImage(parentActivity.getContentResolver(), savedImageBitmap, pageTitle.getDisplayText(), galleryItem.getName()); if (localUrl == null) { throw new RuntimeException(getString(R.string.gallery_save_error_mediastore)); } return localUrl; } @Override public void onFinish(String localUrl) { if (!isAdded()) { return; } FeedbackUtil.showMessage(parentActivity, R.string.gallery_save_success); displayImageSavedNotification(galleryItem, savedImageBitmap, localUrl); } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } FeedbackUtil.showError(parentActivity, caught); } }.execute(); }</code><technical_language>a change new this patch a surprised need a copy of this based experience share a fact</technical_language>

Target:
private void saveImageToMediaStore() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGallerySave(pageTitle, galleryItem.getName()); final Bitmap savedImageBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); new SaneAsyncTask<String>(SaneAsyncTask.SINGLE_THREAD) { @Override public String performTask() throws Throwable { String localUrl = MediaStore.Images.Media.insertImage(parentActivity.getContentResolver(), savedImageBitmap, pageTitle.getDisplayText(), galleryItem.getName()); if (localUrl == null) { throw new RuntimeException(getString(R.string.gallery_save_error_mediastore)); } return localUrl; } @Override public void onFinish(String localUrl) { if (!isAdded()) { return; } FeedbackUtil.showMessage(parentActivity, R.string.gallery_save_success); SavedImageNotificationHelper.displayImageSavedNotification(imageTitle.getText(), imageTitle.getCanonicalUri(), savedImageBitmap, localUrl); } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } FeedbackUtil.showError(parentActivity, caught); } }.execute(); }
Source:
<code>private void progressTo(ShardAndStrategy shardStrategy, long newProgress) { if (newProgress < 0) { log.warn("Wasn't able to progress targeted sweep for since last swept timestamp is negative.", shardStrategy.toText(), newProgress); return; } progress.updateLastSweptTimestamp(shardStrategy, newProgress); <START> log.info("Progressed last swept timestamp for to {}.", shardStrategy.toText(), newProgress); <END> }</code><technical_language>+1: I toText() method for - this sense</technical_language>

Target:
private void progressTo(ShardAndStrategy shardStrategy, long newProgress) { if (newProgress < 0) { log.warn("Wasn't able to progress targeted sweep for since last swept timestamp is negative.", SafeArg.of("shardStrategy", shardStrategy.toText()), SafeArg.of("timestamp", newProgress)); return; } progress.updateLastSweptTimestamp(shardStrategy, newProgress); log.info("Progressed last swept timestamp for to {}.", SafeArg.of("shardStrategy", shardStrategy.toText()), SafeArg.of("timestamp", newProgress)); }
Source:
<code>public List<Integer> getPartitionIdList() { return partitions.stream() .map(p -> p.id) <START> .sorted() <END> .collect(Collectors.toList()); }</code><technical_language>I order is guaranteed in partitions sort order of Partition is partition ID</technical_language>

Target:
public Set<Integer> getPartitionIdList() { return partitions.stream() .map(p -> p.id) .collect(Collectors.toSet()); }
Source:
<code>private String buildMMPkPath() { File extStorDir = Environment.getExternalStorageDirectory(); String extSDCardDirName = this.getResources().getString(R.string.config_data_sdcard_offline_dir); String filename = this.getString(R.string.config_mmpk_name); <START> String path= extStorDir.getAbsolutePath() <END> + File.separator + extSDCardDirName + File.separator + filename + ".mmpk"; return path; }</code><technical_language>Local variable is redundant, inline</technical_language>

Target:
private String buildMMPkPath() { File extStorDir = Environment.getExternalStorageDirectory(); String extSDCardDirName = this.getResources().getString(R.string.config_data_sdcard_offline_dir); String filename = this.getString(R.string.config_mmpk_name); return extStorDir.getAbsolutePath() + File.separator + extSDCardDirName + File.separator + filename + ".mmpk"; }
Source:
<code><START> public int getADCValue(IOLine ioLine) throws InvalidOperatingModeException, XBeeException { <END> if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); if (ioLine == null) throw new NullPointerException("IO line cannot be null."); ATCommandResponse response = sendATCommand(new ATCommand("IS")); if (response == null || response.getResponseStatus() != ATCommandStatus.OK) throw new XBeeException(XBeeException.INVALID_OPERATION); IOSample ioSample = new IOSample(response.getResponse()); if (!ioSample.hasAnalogValues() || !ioSample.getAnalogValues().containsKey(ioLine)) throw new XBeeException(XBeeException.INVALID_OPERATION); return ioSample.getAnalogValues().get(ioLine); }</code><technical_language>This need revisited throw proper exceptions</technical_language>

Target:
public int getADCValue(IOLine ioLine) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); if (ioLine == null) throw new NullPointerException("IO line cannot be null."); ATCommandResponse response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); if (response == null || response.getResponseStatus() != ATCommandStatus.OK || response == null || response.getResponse().length == 0) throw new XBeeException(XBeeException.INVALID_OPERATION); IOSample ioSample = new IOSample(response.getResponse()); if (!ioSample.hasAnalogValues() || !ioSample.getAnalogValues().containsKey(ioLine)) throw new XBeeException(XBeeException.INVALID_OPERATION); return ioSample.getAnalogValues().get(ioLine); }