auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public FlinkPod decorateFlinkPod(FlinkPod flinkPod) { final Pod basicPod = new PodBuilder(flinkPod.getPod()) .withApiVersion(API_VERSION) .editOrNewMetadata() .withLabels(kubernetesJobManagerParameters.getLabels()) .withAnnotations(kubernetesJobManagerParameters.getAnnotations()) <START> .withOwnerReferences(kubernetesJobManagerParameters.getOwnerReference().stream() <END> .map(e -> KubernetesOwnerReference.fromMap(e).getInternalResource()) .collect(Collectors.toList())) .endMetadata() .editOrNewSpec() .withServiceAccountName(kubernetesJobManagerParameters.getServiceAccount()) .withImagePullSecrets(kubernetesJobManagerParameters.getImagePullSecrets()) .withNodeSelector(kubernetesJobManagerParameters.getNodeSelector()) .withTolerations(kubernetesJobManagerParameters.getTolerations().stream() .map(e -> KubernetesToleration.fromMap(e).getInternalResource()) .collect(Collectors.toList())) .endSpec() .build(); final Container basicMainContainer = decorateMainContainer(flinkPod.getMainContainer()); return new FlinkPod.Builder(flinkPod) .withPod(basicPod) .withMainContainer(basicMainContainer) .build(); }</code><technical_language>I afraid set owner reference JobManager pod. I set owner reference JobManager deployment. this piece of codes moved KubernetesJobManagerFactory#createJobManagerDeployment</technical_language>

Target:
public FlinkPod decorateFlinkPod(FlinkPod flinkPod) { final Pod basicPod = new PodBuilder(flinkPod.getPod()) .withApiVersion(API_VERSION) .editOrNewMetadata() .withLabels(kubernetesJobManagerParameters.getLabels()) .withAnnotations(kubernetesJobManagerParameters.getAnnotations()) .endMetadata() .editOrNewSpec() .withServiceAccountName(kubernetesJobManagerParameters.getServiceAccount()) .withImagePullSecrets(kubernetesJobManagerParameters.getImagePullSecrets()) .withNodeSelector(kubernetesJobManagerParameters.getNodeSelector()) .withTolerations(kubernetesJobManagerParameters.getTolerations().stream() .map(e -> KubernetesToleration.fromMap(e).getInternalResource()) .collect(Collectors.toList())) .endSpec() .build(); final Container basicMainContainer = decorateMainContainer(flinkPod.getMainContainer()); return new FlinkPod.Builder(flinkPod) .withPod(basicPod) .withMainContainer(basicMainContainer) .build(); }
Source:
<code>private String getMessage(int expectedPreviousSaveNumber, int previousSaveNumber) { <START> StringBuilder message = new StringBuilder(); <END> message.append("Expected previous saved id was: "); message.append(expectedPreviousSaveNumber); message.append("\nPrevious saved id is: "); message.append(previousSaveNumber); message.append("\n"); return message.toString(); }</code><technical_language>This part of another Gerrit (according commit message)</technical_language>

Target:
private String getMessage(int expectedPreviousSaveNumber, int previousSaveNumber) { StringBuffer message = new StringBuffer(); message.append("Expected previous saved id was: "); message.append(expectedPreviousSaveNumber); message.append("\nPrevious saved id is: "); message.append(previousSaveNumber); message.append("\n"); return message.toString(); }
Source:
<code>public Builder() { super(DefaultReport::new); <START> _schedule = NeverSchedule.getInstance(); <END> _groups = Collections.emptySet(); }</code><technical_language>nit: move defaults member declarations</technical_language>

Target:
public Builder() { super(DefaultReport::new); }
Source:
<code>public void setUp() { cmd = spy(new ReconstructMasterDomainCommand<>(new ReconstructMasterParameters())); storagePoolIsoMap = new StoragePoolIsoMap(storageDomainId, storagePoolId, StorageDomainStatus.Active); StorageDomain storageDomain = new StorageDomain(); storageDomain.setStoragePoolIsoMapData(storagePoolIsoMap); <START> StoragePoolIsoMapDAO storagePoolIsoMapDao = mock(StoragePoolIsoMapDAO.class); <END> doReturn(Collections.singletonList(storagePoolIsoMap)).when(storagePoolIsoMapDao).getAllForStoragePool(storagePoolId); StoragePool storagePool = new StoragePool(); storagePool.setId(storagePoolId); StoragePoolValidator storagePoolValidator = spy(new StoragePoolValidator(storagePool)); doReturn(storagePoolIsoMapDao).when(storagePoolValidator).getStoragePoolIsoMapDao(); doReturn(storageDomain).when(cmd).getStorageDomain(); doReturn(storagePool).when(cmd).getStoragePool(); doReturn(storagePoolValidator).when(cmd).createStoragePoolValidator(); }</code><technical_language>mock in do that.. @Mock private StoragePoolIsoMapDAO storagePoolIsoMapDao;</technical_language>

Target:
public void setUp() { cmd = spy(new ReconstructMasterDomainCommand<>(new ReconstructMasterParameters())); masterDomainIsoMap = new StoragePoolIsoMap(masterStorageDomainId, storagePoolId, StorageDomainStatus.Active); regularDomainIsoMap = new StoragePoolIsoMap(regularStorageDomainId, storagePoolId, StorageDomainStatus.Active); StorageDomain masterStorageDomain = new StorageDomain(); masterStorageDomain.setStoragePoolIsoMapData(masterDomainIsoMap); doReturn(Arrays.asList(masterDomainIsoMap, regularDomainIsoMap)).when(storagePoolIsoMapDao).getAllForStoragePool(storagePoolId); StoragePool storagePool = new StoragePool(); storagePool.setId(storagePoolId); StoragePoolValidator storagePoolValidator = spy(new StoragePoolValidator(storagePool)); doReturn(storagePoolIsoMapDao).when(storagePoolValidator).getStoragePoolIsoMapDao(); doReturn(masterStorageDomain).when(cmd).getStorageDomain(); doReturn(storagePool).when(cmd).getStoragePool(); doReturn(storagePoolValidator).when(cmd).createStoragePoolValidator(); }
Source:
<code>public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); AmqpAcknowledgementHandler ackHandler = createAcknowledgementHandler( getChannel(), consumerTag, deliveryTag, amqpBrokerConfig.isRequeueRejectedMessages()); try { Charset charset = amqpBrokerConfig.getCharset(); String bodyStr = new String(body, charset); <START> LOG.debug(String.format("[consumer tag: %s] Message consumed from broker: %s", consumerTag, bodyStr)); <END> try { consumerThreadPool.submit(new AmqpMessageProcessingTask(consumerTag, bodyStr, msgHandler, ackHandler)); LOG.debug(String.format("[consumer tag: %s] Message has been put in the processing queue: %s.", consumerTag, bodyStr)); } catch (Exception e) { LOG.error(String.format("[consumer tag: %s] Couldn't put message in the processing queue: %s.", consumerTag, bodyStr), e); throw e; } } catch (Exception e) { LOG.error(String.format("[consumer tag: %s] Got exception while processing incoming message. About to send AMQP reject...", consumerTag), e); ackHandler.autoReject(); } }</code><technical_language>acknowledgement logic is changed auto-ack messages consumed queue task thread pool executed. I is cool need change logic for shutdown of thread pool. longer need wait tasks queue complete. sufficient wait for completion of running tasks</technical_language>

Target:
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); AmqpAcknowledgementHandler ackHandler = createAcknowledgementHandler( getChannel(), consumerTag, deliveryTag, envelope.isRedeliver()); try { Charset charset = amqpBrokerConfig.getCharset(); String bodyStr = new String(body, charset); LOG.debug(String.format("[consumer tag: %s] Message consumed from broker: %s", consumerTag, bodyStr)); try { consumerThreadPool.submit(new AmqpMessageProcessingTask(consumerTag, bodyStr, msgHandler, ackHandler)); LOG.debug(String.format("[consumer tag: %s] Message has been put in the processing queue: %s.", consumerTag, bodyStr)); } catch (Exception e) { LOG.error(String.format("[consumer tag: %s] Couldn't put message in the processing queue: %s.", consumerTag, bodyStr), e); throw e; } } catch (Exception e) { LOG.error(String.format("[consumer tag: %s] Got exception while processing incoming message. About to send AMQP reject...", consumerTag), e); ackHandler.autoReject(); } }
Source:
<code>private boolean verifyMetricsFromSinkOnce(Map<String, Long> expectedMetrics) { synchronized (GlobalPhoenixMetricsTestSink.lock) { for (AbstractMetric metric : GlobalPhoenixMetricsTestSink.metrics) { if (expectedMetrics.containsKey(metric.name())) { long expectedValue = expectedMetrics.get(metric.name()); long actualValue = metric.value().longValue(); if (expectedValue != actualValue) { LOG.warn("Metric from Hadoop Sink: " + metric.name() + " didn't match expected."); <START> return false; <END> } expectedMetrics.remove(metric.name()); } } } assertTrue("Metric expected but not present in Hadoop Metrics Sink (GlobalPhoenixMetricsTestSink)", expectedMetrics.size() == 0); return true; }</code><technical_language>I thought issue unboxing expectedMetrics.get(metric.name()). I cleaner do: Long = expectedMetrics.get(metric.name()); if (value != null) { long expectedValue = value.longValue(); ..</technical_language>

Target:
private boolean verifyMetricsFromSinkOnce(Map<String, Long> expectedMetrics) { synchronized (GlobalPhoenixMetricsTestSink.lock) { for (AbstractMetric metric : GlobalPhoenixMetricsTestSink.metrics) { if (expectedMetrics.containsKey(metric.name())) { Long value = expectedMetrics.get(metric.name()); if (value != null) { long expectedValue = value; long actualValue = metric.value().longValue(); if (expectedValue != actualValue) { LOG.warn("Metric from Hadoop Sink: " + metric.name() + " didn't match expected."); return false; } expectedMetrics.remove(metric.name()); } } } } assertTrue("Metric expected but not present in Hadoop Metrics Sink (GlobalPhoenixMetricsTestSink)", expectedMetrics.size() == 0); return true; }
Source:
<code>public void teardown() throws Exception { super.teardown(); if (auxFs != null) { <START> auxFs.delete(testRoot, true); <END> } }</code><technical_language>this need auxFs.close()</technical_language>

Target:
public void teardown() throws Exception { super.teardown(); if (auxFs != null) { auxFs.delete(testRoot, true); auxFs.close(); } }
Source:
<code>protected Builder() { super(DockerApi.class); id("docker") .name("Docker API") .identityName("user") .credentialName("password") .documentation(URI.create("<LINK_1>")) <START> .version("1.15") <END> .defaultEndpoint("<LINK_0>") .defaultProperties(DockerApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)) .defaultModules(ImmutableSet.<Class<? extends Module>>of( DockerParserModule.class, DockerHttpApiModule.class, DockerComputeServiceContextModule.class)); }</code><technical_language>oo fancy</technical_language>

Target:
protected Builder() { super(DockerApi.class); id("docker") .name("Docker API") .identityName("Path to Certificate .p12 file") .credentialName("Password to Certificate") .documentation(URI.create("<LINK_1>")) .version("1.15") .defaultEndpoint("<LINK_0>") .defaultProperties(DockerApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)) .defaultModules(ImmutableSet.<Class<? extends Module>>of( DockerParserModule.class, DockerHttpApiModule.class, DockerComputeServiceContextModule.class)); }
Source:
<code>public void testCreateTableWithNotNull() { assertStatement("CREATE TABLE foo (" + "a VARCHAR NOT NULL COMMENT 'column a', " + "b BIGINT COMMENT 'hello world', " + "c IPADDRESS, " + "d DATE NOT NULL)", <START> new CreateTable(QualifiedName.of("foo"), <END> ImmutableList.of( new ColumnDefinition(identifier("a"), "VARCHAR", emptyList(), Optional.of("column a"), false), new ColumnDefinition(identifier("b"), "BIGINT", emptyList(), Optional.of("hello world"), true), new ColumnDefinition(identifier("c"), "IPADDRESS", emptyList(), Optional.empty(), true), new ColumnDefinition(identifier("d"), "DATE", emptyList(), Optional.empty(), false)), false, ImmutableList.of(), Optional.empty())); }</code><technical_language>\n QualifiedName.</technical_language>

Target:
public void testCreateTableWithNotNull() { assertStatement( "CREATE TABLE foo (" + "a VARCHAR NOT NULL COMMENT 'column a', " + "b BIGINT COMMENT 'hello world', " + "c IPADDRESS, " + "d DATE NOT NULL)", new CreateTable( QualifiedName.of("foo"), ImmutableList.of( new ColumnDefinition(identifier("a"), "VARCHAR", false, emptyList(), Optional.of("column a")), new ColumnDefinition(identifier("b"), "BIGINT", true, emptyList(), Optional.of("hello world")), new ColumnDefinition(identifier("c"), "IPADDRESS", true, emptyList(), Optional.empty()), new ColumnDefinition(identifier("d"), "DATE", false, emptyList(), Optional.empty())), false, ImmutableList.of(), Optional.empty())); }
Source:
<code>public int getMaxDamage() { if (itemMaterial == null) { return 0; } else { return itemMaterial.getMaxDamage(); <START> } <END> }</code><technical_language>simplified java return itemMaterial == null ? 0 : itemMaterial.getMaxDamage();</technical_language>

Target:
public int getMaxDamage() { return itemMaterial.getMaxDamage(); }
Source:
<code>private String getCombinedLabels(IThreadDMContext processDmc, IMIExecutionDMContext execDmc) { IThreadDMData processData = getData(processDmc); String label = getLabel(processData); if (execDmc != null) { <START> int threadId; <END> try { threadId = Integer.parseInt(execDmc.getThreadId()); label += !label.isEmpty() ? ": " : ""; label += "Thread [" + Integer.toString(threadId) + "]"; } catch (NumberFormatException e) { } } return label; }</code><technical_language>In this block, avoid conversions(String -> int, int -> String), String returned execDmc.getThreadId()? this code ready handle "new" thread ids change</technical_language>

Target:
private String getCombinedLabels(IThreadDMContext processDmc, IMIExecutionDMContext execDmc) { IThreadDMData processData = getData(processDmc); String label = getLabel(processData); if (execDmc != null) { String threadId = execDmc.getThreadId(); label += !label.isEmpty() ? ": " : ""; label += "Thread [" + threadId + "]"; } return label; }
Source:
<code>TimestampsByCellResultWithToken moveForward(Token oldToken) { boolean skipping = oldToken.shouldSkip(); while (skipping && iterator.hasNext()) { AgnosticLightResultRow nextResult = iterator.peek(); <START> if (finishedForwarding(oldToken, nextResult)) { <END> skipping = false; } else { iterator.next(); } } return this; }</code><technical_language>Oops, missed a rename: finishedForwarding -> finishedSkipping</technical_language>

Target:
private TimestampsByCellResultWithToken moveForward(Token oldToken) { boolean skipping = oldToken.shouldSkip(); while (skipping && iterator.hasNext()) { AgnosticLightResultRow nextResult = iterator.peek(); if (finishedSkipping(oldToken, nextResult)) { skipping = false; } else { iterator.next(); } } entries.putAll(rowBuffer); return this; }
Source:
<code>public void test_primary_key_in_pg_index() { execute(" select i.* from pg_index i, pg_class c where c.relname = 't1' and c.oid = i.indrelid;"); assertThat(printedTable(response.rows()), is( <START> "false| NULL| NULL| NULL| -649073482| true| false| false| true| true| true| false| false| true| [1]| 0| NULL| NULL| 728874843\n" <END> )); }</code><technical_language>sense reduce this columns relevant</technical_language>

Target:
public void test_primary_key_in_pg_index() { execute(" select i.indexrelid, i.indrelid, i.indkey from pg_index i, pg_class c where c.relname = 't1' and c.oid = i.indrelid;"); assertThat(printedTable(response.rows()), is("-649073482| 728874843| [1]\n")); }
Source:
<code>default void onDuplicate(I target, CommandEnvelope envelope) { repository().lifecycleOf(target) <START> .onDuplicateCommand(envelope.messageId()); <END> }</code><technical_language>Is other ID in relation envelope? do need a longer name in this context</technical_language>

Target:
default void onDuplicate(I target, CommandEnvelope envelope) { repository().lifecycleOf(target) .onDuplicateCommand(envelope); }
Source:
<code>private TaCoKitElementParameter visitSchema(final PropertyNode node) { final String connectorName = node.getProperty().getConnection().getValue(); final EConnectionType connectorType = connectorName.equalsIgnoreCase("reject") ? EConnectionType.REJECT <START> : EConnectionType.FLOW_MAIN; <END> final String connectionName; if (connectorName.equals("__default__")) { connectionName = EConnectionType.FLOW_MAIN.getName(); } else if (connectorType == EConnectionType.REJECT) { connectionName = EConnectionType.REJECT.getName(); } else { connectionName = connectorName; } final String schemaName = node.getProperty().getSchemaName(); return createSchemaParameter(connectionName, schemaName, true); }</code><technical_language>note EConnectionType connectorType boolean isReject = connectorName.equalsIgnoreCase("reject"); if (isReject) { connectionName = EConnectionType.REJECT.getName(); } do simpler: } else if (connectorName.equalsIgnoreCase("reject")) { connectionName = EConnectionType.REJECT.getName(); } so, is need connectorType</technical_language>

Target:
private TaCoKitElementParameter visitSchema(final PropertyNode node) { final String connectorName = node.getProperty().getConnection().getValue(); final String connectionName; if (connectorName.equals("__default__")) { connectionName = EConnectionType.FLOW_MAIN.getName(); } else if (connectorName.equalsIgnoreCase(EConnectionType.REJECT.getName())) { connectionName = EConnectionType.REJECT.getName(); } else { connectionName = connectorName; } final String schemaName = node.getProperty().getSchemaName(); return createSchemaParameter(connectionName, schemaName, true); }
Source:
<code>public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("application/gzip"); response.setStatus(HttpServletResponse.SC_OK); try { int currByteWritten = -1; int numBytesWritten = 0; InputStream in = new ByteArrayInputStream(RESPONSE_STR.getBytes()); OutputStream out = response.getOutputStream(); while ((currByteWritten = in.read()) != -1) { out.write(currByteWritten); out.flush(); numBytesWritten++; if (numBytesWritten >= THRESHOLD_BYTES) { <START> serverWaitLatch.await(); <END> } } } catch(Exception e) { LOG.error("{}", e); serverException = e; } }</code><technical_language>I is TIMEOUT version of await() avoid test hanging failure</technical_language>

Target:
public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("application/gzip"); response.setStatus(HttpServletResponse.SC_OK); try { int currByteWritten = -1; int numBytesWritten = 0; InputStream in = new ByteArrayInputStream(RESPONSE_STR.getBytes()); OutputStream out = response.getOutputStream(); while ((currByteWritten = in.read()) != -1) { out.write(currByteWritten); out.flush(); numBytesWritten++; if (numBytesWritten >= THRESHOLD_BYTES) { if(!serverWaitLatch.await(5, TimeUnit.SECONDS)) { throw new IOException("Timed out waiting for latch"); } break; } } } catch(Exception e) { LOG.error("{}", e); serverException = e; } }
Source:
<code>public void checkNoDuplicateIdInSpec(AadlPackage toppkg) { Set<AadlPackage> pkgs = new HashSet<>(); getPackageDependencies(toppkg, pkgs); HashMultimap<String, SpecStatement> multiMap = HashMultimap.create(); for (AadlPackage pkg : pkgs) { List<NamedSpecStatement> specs = getNamedSpecStatements(pkg); for (NamedSpecStatement spec : specs) { String id = spec.getName(); if (id != null) { multiMap.put(id, spec); } } } List<NamedSpecStatement> specs = getNamedSpecStatements(toppkg); for (NamedSpecStatement spec : specs) { String id = spec.getName(); if (multiMap.get(id).size() > 1) { <START> error("Duplicate ID in AGREE claim", spec, Aadl2Package.eINSTANCE.getNamedElement_Name()); <END> } } }</code><technical_language>This error message is showing in console in test, refer syntax. Is a get rid of duplicate error message? helpful for error message state package duplicated ID</technical_language>

Target:
public void checkNoDuplicateIdInSpec(AadlPackage toppkg) { HashMultimap<String, NamedSpecStatement> namedSpecs = HashMultimap.create(); Set<AadlPackage> pkgs = new HashSet<>(); getPackageDependencies(toppkg, pkgs); for (AadlPackage pkg : pkgs) { List<NamedSpecStatement> specs = getNamedSpecStatements(pkg); for (NamedSpecStatement spec : specs) { String id = spec.getName(); if (id != null) { namedSpecs.put(id, spec); } } } List<NamedSpecStatement> specs = getNamedSpecStatements(toppkg); Iterator<NamedSpecStatement> i = specs.iterator(); while (i.hasNext()) { NamedSpecStatement spec = i.next(); String id = spec.getName(); if (namedSpecs.get(id).size() > 1) { Iterator<NamedSpecStatement> ii = namedSpecs.get(id).iterator(); while (ii.hasNext()) { String pkgName = AadlUtil.getContainingPackage(ii.next()).getName(); if (!pkgName.contentEquals(AadlUtil.getContainingPackage(spec).getName())) { error("Duplicate AGREE property ID in package " + pkgName, spec, Aadl2Package.eINSTANCE.getNamedElement_Name()); } } namedSpecs.removeAll(id); } } }
Source:
<code>private Credential getCredential(Configuration config) throws IOException, GeneralSecurityException { Credential credential = null; if (delegationTokens != null) { AccessTokenProvider atp = delegationTokens.getAccessTokenProvider(); if (atp != null) { atp.setConf(config); credential = CredentialFromAccessTokenProviderClassFactory.credential( atp, CredentialFactory.GCS_SCOPES); } } else { credential = CredentialFromAccessTokenProviderClassFactory.credential( config, ImmutableList.of(GCS_CONFIG_PREFIX), CredentialFactory.GCS_SCOPES); if (credential == null) { credential = HadoopCredentialConfiguration.getCredentialFactory(config, GCS_CONFIG_PREFIX) .getCredential(CredentialFactory.GCS_SCOPES); } } String impersonationServiceAccount = HadoopCredentialConfiguration.getImpersonationServiceAccount(config, GCS_CONFIG_PREFIX); if (impersonationServiceAccount != null) { GoogleCloudStorageOptions options = GoogleHadoopFileSystemConfiguration.getGcsFsOptionsBuilder(config) .build() .getCloudStorageOptions(); HttpRequestInitializer initializer = new RetryHttpInitializer( checkNotNull(credential, "credential must not be null"), options.getAppName(), options.getMaxHttpRequestRetries(), options.getHttpRequestConnectTimeout(), options.getHttpRequestReadTimeout(), options.getHttpRequestHeaders()); HttpTransport httpTransport = HttpTransportFactory.createHttpTransport( options.getTransportType(), options.getProxyAddress(), options.getProxyUsername(), options.getProxyPassword()); <START> GoogleCloudStorageAccessTokenProvider internalAccessTokenProvider = <END> new GoogleCloudStorageAccessTokenProvider( impersonationServiceAccount, initializer, httpTransport, CredentialFactory.CLOUD_PLATFORM_SCOPES); internalAccessTokenProvider.setConf(config); credential = CredentialFromAccessTokenProviderClassFactory.getCredentialFromAccessTokenProvider( internalAccessTokenProvider, CredentialFactory.GCS_SCOPES); } return credential; }</code><technical_language>extract this logic in util project, in ImpersonatedCredentialsFactory class</technical_language>

Target:
private Credential getCredential(Configuration config) throws IOException, GeneralSecurityException { Credential credential = null; if (delegationTokens != null) { AccessTokenProvider atp = delegationTokens.getAccessTokenProvider(); if (atp != null) { atp.setConf(config); credential = CredentialFromAccessTokenProviderClassFactory.credential( atp, CredentialFactory.GCS_SCOPES); } } else { credential = CredentialFromAccessTokenProviderClassFactory.credential( config, ImmutableList.of(GCS_CONFIG_PREFIX), CredentialFactory.GCS_SCOPES); if (credential == null) { credential = HadoopCredentialConfiguration.getCredentialFactory(config, GCS_CONFIG_PREFIX) .getCredential(CredentialFactory.GCS_SCOPES); } } return getImpersonatedCredential(config, credential).orElse(credential); }
Source:
<code>public void send(final CoreLogItemRequestMessage coreLogItemRequestMessage) { LOGGER.debug("Sending CoreLogItemRequestMessage"); this.coreLogItemRequestsJmsTemplate.send(new MessageCreator() { @Override public Message createMessage(final Session session) throws JMSException { final ObjectMessage objectMessage = session.createObjectMessage(); <START> objectMessage.setJMSType(Constants.DLMS_LOG_ITEM_REQUEST); <END> objectMessage.setStringProperty(Constants.DECODED_MESSAGE, coreLogItemRequestMessage.getDecodedMessage()); objectMessage.setStringProperty(Constants.DEVICE_IDENTIFICATION, coreLogItemRequestMessage.getDeviceIdentification()); if (coreLogItemRequestMessage.hasOrganisationIdentification()) { objectMessage.setStringProperty(Constants.ORGANISATION_IDENTIFICATION, coreLogItemRequestMessage.getOrganisationIdentification()); } objectMessage.setStringProperty(Constants.IS_VALID, coreLogItemRequestMessage.isValid().toString()); objectMessage.setIntProperty(Constants.PAYLOAD_MESSAGE_SERIALIZED_SIZE, coreLogItemRequestMessage.getPayloadMessageSerializedSize()); return objectMessage; } }); }</code><technical_language>DLMS_LOG_ITEM_REQUEST, create a new constant</technical_language>

Target:
public void send(final CoreLogItemRequestMessage coreLogItemRequestMessage) { LOGGER.debug("Sending CoreLogItemRequestMessage"); this.coreLogItemRequestsJmsTemplate.send(new MessageCreator() { @Override public Message createMessage(final Session session) throws JMSException { final ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setJMSType(Constants.CORE_LOG_ITEM_REQUEST); objectMessage.setStringProperty(Constants.DECODED_MESSAGE, coreLogItemRequestMessage.getDecodedMessage()); objectMessage.setStringProperty(Constants.DEVICE_IDENTIFICATION, coreLogItemRequestMessage.getDeviceIdentification()); if (coreLogItemRequestMessage.hasOrganisationIdentification()) { objectMessage.setStringProperty(Constants.ORGANISATION_IDENTIFICATION, coreLogItemRequestMessage.getOrganisationIdentification()); } objectMessage.setStringProperty(Constants.IS_VALID, coreLogItemRequestMessage.isValid().toString()); objectMessage.setIntProperty(Constants.PAYLOAD_MESSAGE_SERIALIZED_SIZE, coreLogItemRequestMessage.getPayloadMessageSerializedSize()); return objectMessage; } }); }
Source:
<code>public static void main(String[] args) { if (args.length > 1) { final String destBasePath = args[0]; final List<String> filesToCopy = Arrays.asList(args).subList(1, args.length); copyTemplateFiles(destBasePath, filesToCopy); } else { <START> throw new RuntimeException("Missing arguments, required at least one origin paths"); <END> } }</code><technical_language>Missing arguments, required origin path (without s)</technical_language>

Target:
public static void main(String[] args) { if (args.length > 1) { final String destBasePath = args[0]; final List<String> filesToCopy = Arrays.asList(args).subList(1, args.length); copyTemplateFiles(destBasePath, filesToCopy); } else { throw new RuntimeException("Missing arguments, required at least one origin path"); } }
Source:
<code>public void showSavePopup(Path path, Command saveCommand, Command cancelCommand) { YesNoCancelPopup popup = YesNoCancelPopup.newYesNoCancelPopup(path.getFileName(), <START> "", <END> saveCommand, CommonConstants.INSTANCE.Save(), null, null, cancelCommand, CommonConstants.INSTANCE.Cancel()); popup.show(); }</code><technical_language>popup appears blank! a message</technical_language>

Target:
public void showSavePopup(Path path, Command saveCommand, Command cancelCommand) { YesNoCancelPopup popup = YesNoCancelPopup.newYesNoCancelPopup(org.uberfire.ext.widgets.common.client.resources.i18n.CommonConstants.INSTANCE.Information(), translationService.getTranslation(FormEditorConstants.FormEditorViewImplSaveBeforeRename), saveCommand, CommonConstants.INSTANCE.Save(), null, null, cancelCommand, translationService.getTranslation(FormEditorConstants.FormEditorViewImplDontSave)); popup.show(); }
Source:
<code>public static boolean isInvocationOnVariable(MethodInvocationTree mit, @Nullable Symbol variable, boolean defaultReturn) { ExpressionTree methodSelect = mit.methodSelect(); if (variable != null && methodSelect.is(Tree.Kind.MEMBER_SELECT)) { Optional<Symbol> extractedSymbol = extractIdentifierSymbol(((MemberSelectExpressionTree) methodSelect).expression()); if (extractedSymbol.isPresent()) { return extractedSymbol.get().equals(variable); } } return defaultReturn; <START> } <END></code><technical_language>reduce cognitive complexity 1 using: public static boolean isInvocationOnVariable(MethodInvocationTree mit, @Nullable Symbol variable, boolean defaultReturn) { ExpressionTree methodSelect = mit.methodSelect(); if (variable != null && methodSelect.is(Tree.Kind.MEMBER_SELECT)) { return extractIdentifierSymbol(((MemberSelectExpressionTree) methodSelect).expression()) .map(variable::equals) .orElse(defaultReturn); } return defaultReturn; } public static boolean isInvocationOnVariable(MethodInvocationTree mit, @Nullable Symbol variable, boolean defaultReturn) { ExpressionTree methodSelect = mit.methodSelect(); if (variable == null || !methodSelect.is(Tree.Kind.MEMBER_SELECT)) { return defaultReturn; } return extractIdentifierSymbol(((MemberSelectExpressionTree) methodSelect).expression()) .map(variable::equals) .orElse(defaultReturn); }</technical_language>

Target:
public static boolean isInvocationOnVariable(MethodInvocationTree mit, @Nullable Symbol variable, boolean defaultReturn) { ExpressionTree methodSelect = mit.methodSelect(); if (variable == null || !methodSelect.is(Tree.Kind.MEMBER_SELECT)) { return defaultReturn; } return extractIdentifierSymbol(((MemberSelectExpressionTree) methodSelect).expression()) .map(variable::equals) .orElse(defaultReturn); }
Source:
<code>public PaxosLeaderElectionService(PaxosProposer proposer, PaxosLearner knowledge, Map<PingableLeader, HostAndPort> potentialLeadersToHosts, List<PaxosAcceptor> acceptors, List<PaxosLearner> learners, ExecutorService executor, long updatePollingWaitInMs, long randomWaitBeforeProposingLeadership, long leaderPingResponseWaitMs) { this(proposer, knowledge, potentialLeadersToHosts, acceptors, learners, executor, updatePollingWaitInMs, randomWaitBeforeProposingLeadership, , DEFAULT_NO_QUORUM_MAX_DELAY_MS, leaderPingResponseWaitMs, PaxosLeaderElectionEventRecorder.NO_OP); <START> } <END></code><technical_language>double comma</technical_language>

Target:
public PaxosLeaderElectionService(PaxosProposer proposer, PaxosLearner knowledge, Map<PingableLeader, HostAndPort> potentialLeadersToHosts, List<PaxosAcceptor> acceptors, List<PaxosLearner> learners, ExecutorService executor, long updatePollingWaitInMs, long randomWaitBeforeProposingLeadership, long leaderPingResponseWaitMs) { this(proposer, knowledge, potentialLeadersToHosts, acceptors, learners, executor, updatePollingWaitInMs, randomWaitBeforeProposingLeadership, DEFAULT_NO_QUORUM_MAX_DELAY_MS, leaderPingResponseWaitMs, PaxosLeaderElectionEventRecorder.NO_OP); }
Source:
<code>public VcrMetrics(MetricRegistry registry) { this.registry = registry; blobEncryptionCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionCount")); <START> blobDecryptionCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobDet4acryptionCount")); <END> blobEncryptionTime = registry.timer(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionTime")); blobDecryptionTime = registry.timer(MetricRegistry.name(CloudBlobStore.class, "BlobDecryptionTime")); }</code><technical_language>Typo? "BlobDet4acryptionCount"</technical_language>

Target:
public VcrMetrics(MetricRegistry registry) { this.registry = registry; blobEncryptionCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionCount")); blobDecryptionCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobDecryptionCount")); blobEncryptionTime = registry.timer(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionTime")); blobDecryptionTime = registry.timer(MetricRegistry.name(CloudBlobStore.class, "BlobDecryptionTime")); }
Source:
<code>private Maybe<Image> getImage(Element element) { Elements imageElements = element.getFirstChildElement("images").getChildElements("image"); if (imageElements.size() > 0) { String image = imageElements.get(0).getValue(); <START> if(!image.contains("http")) { <END> image = "http://" + image; } Image imageObj = new Image(image); if (image.contains("api-images.channel5.com/images/default")) { imageObj.setType(ImageType.GENERIC_IMAGE_CONTENT_PLAYER); } return Maybe.just(imageObj); } return Maybe.nothing(); }</code><technical_language>this check</technical_language>

Target:
private Maybe<Image> getImage(Element element) { Elements imageElements = element.getFirstChildElement("images").getChildElements("image"); if (imageElements.size() > 0) { String image = imageElements.get(0).getValue(); if(!image.contains("http://")) { image = "http://" + image; } Image imageObj = new Image(image); if (image.contains("api-images.channel5.com/images/default")) { imageObj.setType(ImageType.GENERIC_IMAGE_CONTENT_PLAYER); } return Maybe.just(imageObj); } return Maybe.nothing(); }
Source:
<code>public void doesNotLogIfClockDoesNotGoBackwards() { when(delegate.getSystemTimeInNanos()) .thenReturn(1L) .thenReturn(2L) .thenReturn(3L); <START> clock.getSystemTimeInNanos(); <END> }</code><technical_language>call 3 times here</technical_language>

Target:
public void doesNotLogIfClockDoesNotGoBackwards() { when(delegate.getSystemTimeInNanos()) .thenReturn(1L) .thenReturn(2L) .thenReturn(3L); clock.getSystemTimeInNanos(); clock.getSystemTimeInNanos(); clock.getSystemTimeInNanos(); }
Source:
<code>public void attach(final ChannelCreationListener channelCreationListener) { this.channelCreationListener = channelCreationListener; newChannelName.addTextChangedListener(channelNameTextWatcher); toolbar.setOnMenuItemClickListener(menuItemClickListener); toolbar.setNavigationOnClickListener(navigationOnClickListener); <START> toolbar.getMenu().getItem(0).setEnabled(false); <END> }</code><technical_language>this? a more descriptive name</technical_language>

Target:
public void attach(final ChannelCreationListener channelCreationListener) { this.channelCreationListener = channelCreationListener; newChannelName.addTextChangedListener(channelNameTextWatcher); toolbar.setOnMenuItemClickListener(menuItemClickListener); toolbar.setNavigationOnClickListener(navigationOnClickListener); getCreateItem().setEnabled(false); }
Source:
<code>public Type getTypeBound() { <START> Type boundingBase = this; <END> if ( typeMirror.getKind() == TypeKind.WILDCARD ) { WildcardType wildCardType = (WildcardType) typeMirror; if ( wildCardType.getExtendsBound() != null ) { boundingBase = typeFactory.getType( wildCardType.getExtendsBound() ); } else if ( wildCardType.getSuperBound() != null ) { boundingBase = typeFactory.getType( wildCardType.getSuperBound() ); } else { String wildCardName = wildCardType.toString(); if ( "?".equals( wildCardName ) ) { boundingBase = typeFactory.getType( Object.class ); } } } else if ( typeMirror.getKind() == TypeKind.TYPEVAR ) { TypeVariable typeVariableType = (TypeVariable) typeMirror; if ( typeVariableType.getUpperBound() != null ) { boundingBase = typeFactory.getType( typeVariableType.getUpperBound() ); } } return boundingBase; }</code><technical_language>I details, this method a expensive operation, possibly invoked times for types (e.g. I in templates). sense cache result in a field</technical_language>

Target:
public Type getTypeBound() { if ( boundingBase != null ) { return boundingBase; } boundingBase = this; if ( typeMirror.getKind() == TypeKind.WILDCARD ) { WildcardType wildCardType = (WildcardType) typeMirror; if ( wildCardType.getExtendsBound() != null ) { boundingBase = typeFactory.getType( wildCardType.getExtendsBound() ); } else if ( wildCardType.getSuperBound() != null ) { boundingBase = typeFactory.getType( wildCardType.getSuperBound() ); } else { String wildCardName = wildCardType.toString(); if ( "?".equals( wildCardName ) ) { boundingBase = typeFactory.getType( Object.class ); } } } else if ( typeMirror.getKind() == TypeKind.TYPEVAR ) { TypeVariable typeVariableType = (TypeVariable) typeMirror; if ( typeVariableType.getUpperBound() != null ) { boundingBase = typeFactory.getType( typeVariableType.getUpperBound() ); } } return boundingBase; }
Source:
<code>public Object getContentObject() { <START> throw new UnsupportedOperationException("Not implemented for JPA"); <END> }</code><technical_language>wha implement this for JPA? bit uncomfortable new methods for type ..</technical_language>

Target:
public Object getContentObject() { return null; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_group); setSupportActionBar((android.support.v7.widget.Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setTitle(null); getSupportActionBar().setDisplayHomeAsUpEnabled(true); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler); recyclerView.addItemDecoration(new GroupReportBackItemDecoration()); adapter = new GroupAdapter(generateSampleData(), this); recyclerView.setAdapter(adapter); <START> GridLayoutManager layoutManager = new GridLayoutManager(this, 6); <END> layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { switch(adapter.getItemViewType(position)) { case GroupAdapter.VIEW_TYPE_FRIEND: return 1; case GroupAdapter.VIEW_TYPE_REPORT_BACK : return 3; default: return 6; } } }); recyclerView.setLayoutManager(layoutManager); int campaignId = getIntent().getIntExtra(EXTRA_CAMPAIGN_ID, - 1); String userId = getIntent().getStringExtra(EXTRA_USER_ID); if(campaignId != - 1) { TaskQueue.loadQueueDefault(this).execute(new CampaignGroupDetailsTask(campaignId, userId)); TaskQueue.loadQueueDefault(this).execute( new IndividualCampaignReportBackList(- 1, Integer.toString(campaignId), currentPage)); } }</code><technical_language>move adapter stuff init() function</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_group); initUI(); int campaignId = getIntent().getIntExtra(EXTRA_CAMPAIGN_ID, - 1); String userId = getIntent().getStringExtra(EXTRA_USER_ID); if(campaignId != - 1) { TaskQueue.loadQueueDefault(this).execute(new CampaignGroupDetailsTask(campaignId, userId)); TaskQueue.loadQueueDefault(this).execute( new IndividualCampaignReportBackList(- 1, Integer.toString(campaignId), currentPage)); } }
Source:
<code><START> public void valueOutOfDefaultLowerRange() { <END> initConfiguredWithDefaultMinValue(); Set<ConstraintViolation<ConfiguredRangeContainer>> validate = validate(new ConfiguredRangeContainer(TEST_DEFAULT_MIN_RANGE - 1)); Assert.assertTrue(validate.size() > 0); }</code><technical_language>This next test in terms of logic, testing "default" min range is a min range is set annotation</technical_language>

Target:
public void valueOutOfDefaultLowerRange() { initConfiguredWithDefaultMinValue(); validateAndAssertResult(new ConfiguredRangeContainerDefaultMin(TEST_DEFAULT_MIN_RANGE - 1), false); }
Source:
<code>public int getParameterCount() { return jjtGetNumChildren() > 0 && getFirstChildOfType(ASTFormalParameter.class).isExplicitReceiverParameter() <START> ? jjtGetNumChildren() - 1 : jjtGetNumChildren(); <END> }</code><technical_language>@jsotuyod Yes, sense ignore explicit receiver parameters for ParameterCount. code complex for determining count - created #1019 track this (and other grammar changes) for PMD 7.0.0. grammar change in place, this: findChildrenOfType(ASTFormalParameter.class).size();</technical_language>

Target:
public int getParameterCount() { final List<ASTFormalParameter> parameters = findChildrenOfType(ASTFormalParameter.class); return !parameters.isEmpty() && parameters.get(0).isExplicitReceiverParameter() ? parameters.size() - 1 : parameters.size(); }
Source:
<code>public String getPath(){ <START> if(getAssetName().equals("system folder") && getParentPath().equals("/System folder")) <END> return "/"; else { String x = getParentPath() + getAssetName(); if("folder".equals(assetType)){ if(! x.endsWith("/")){ x= x + "/"; } } return x; } }</code><technical_language>want constants constant in left side, SYSTEM_FOLDER.equals(getAssetName())</technical_language>

Target:
public String getPath(){ if(("system folder").equals(getAssetName()) && ("/System folder").equals(getParentPath())){ return "/"; } else { String x = getParentPath() + getAssetName(); if("folder".equals(assetType)){ if(! x.endsWith("/")){ x= x + "/"; } } return x; } }
Source:
<code>public void testZeroReconnectAttemptsBadHost() { <START> Assume.assumeTrue("Test does not run on Windows Server", SystemUtils.OS_NAME.contains("Windows Server")); <END> badHostUdpOperation.get(ElytronDescriptionConstants.ICMP_ERROR_RECONNECT_ATTEMPTS).set(0); ModelNode response = services.executeOperation(badHostUdpOperation); assertCorrectError(response, "The maximum icmp-error-reconnect-attempts value of 0 was reached"); assertFailed(response); }</code><technical_language>work Windows 10</technical_language>

Target:
public void testZeroReconnectAttemptsBadHost() { Assume.assumeFalse("Test does not run on Windows Server", SystemUtils.OS_NAME.contains("Windows Server")); badHostUdpOperation.get(ElytronDescriptionConstants.RECONNECT_ATTEMPTS).set(0); ModelNode response = services.executeOperation(badHostUdpOperation); assertCorrectError(response, new String[] {"ELY12001", "0"}); assertFailed(response); }
Source:
<code>public Optional<FlyingData> from(DataHolder dataHolder) { if (supports(dataHolder)) { final SpongeFlyingData flyingData = new SpongeFlyingData(); <START> final boolean flying = ((net.minecraft.entity.Entity) dataHolder).isAirBorne; <END> return Optional.<FlyingData>of(flyingData.setFlying(flying)); } else { return Optional.absent(); } }</code><technical_language>forgetting EntityPlayer checks</technical_language>

Target:
public Optional<FlyingData> from(DataHolder dataHolder) { if (supports(dataHolder)) { boolean flying = ((Entity) dataHolder).isAirBorne; if (dataHolder instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) dataHolder; flying = player.capabilities.isFlying; } final SpongeFlyingData flyingData = new SpongeFlyingData(flying); return Optional.<FlyingData>of(flyingData); } else { return Optional.absent(); } }
Source:
<code>@Theory public void retainsPerSampleRate(int reservoir) throws Exception { Sampler sampler = RateLimitingSampler.create(reservoir); long startTick = System.nanoTime(); long lastDecisecond = startTick + TimeUnit.MILLISECONDS.toNanos(990); long deadline = startTick + TimeUnit.MILLISECONDS.toNanos(998); AtomicBoolean hitLastDecisecond = new AtomicBoolean(); AtomicLong passed = new AtomicLong(); Runnable sample = () -> { long tick = System.nanoTime(); if (tick > deadline) return; if (tick >= lastDecisecond) hitLastDecisecond.set(true); <START> if (sampler.isSampled(0L)) passed.incrementAndGet(); <END> }; ExecutorService service = Executors.newFixedThreadPool(10); List<Future<?>> futures = new ArrayList<>(); do { if (reservoir > 10) { for (int i = 0; i < reservoir / 10; i++) futures.add(service.submit(sample)); } else { service.submit(sample); } for (Future<?> future : futures) future.get(); futures.clear(); Thread.sleep(9); } while (System.nanoTime() < deadline); service.shutdown(); service.awaitTermination(1, TimeUnit.SECONDS); assertThat(passed.get()).isEqualTo(reservoir); assumeThat(hitLastDecisecond.get()) .withFailMessage("ran out of samples before the end of the second") .isTrue(); }</code><technical_language>inject a clock? I notice guava tests easy reason real time. run faster <LINK_0></technical_language>

Target:
@Theory public void retainsPerSampleRate(int reservoir) throws Exception { Sampler sampler = RateLimitingSampler.create(reservoir); long startTick = System.nanoTime(); long lastDecisecond = startTick + TimeUnit.MILLISECONDS.toNanos(990); long deadline = startTick + TimeUnit.MILLISECONDS.toNanos(998); AtomicBoolean hitLastDecisecond = new AtomicBoolean(); AtomicLong passed = new AtomicLong(); Runnable sample = () -> { long tick = System.nanoTime(); if (tick > deadline) return; if (tick >= lastDecisecond) hitLastDecisecond.set(true); if (sampler.isSampled(0L)) passed.incrementAndGet(); }; Runnable loopAndSample = () -> { do { if (reservoir > 10) { for (int j = 0; j < reservoir / 10; j++) sample.run(); } else { sample.run(); } sleepUninterruptibly(9, TimeUnit.MILLISECONDS); } while (System.nanoTime() < deadline); }; int threadCount = 10; ExecutorService service = Executors.newFixedThreadPool(threadCount); List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < threadCount; i++) { futures.add(service.submit(loopAndSample)); } service.shutdown(); service.awaitTermination(1, TimeUnit.SECONDS); assertThat(passed.get()).isEqualTo(reservoir); assumeThat(hitLastDecisecond.get()) .withFailMessage("ran out of samples before the end of the second") .isTrue(); }
Source:
<code>public synchronized void onBlobReplicaCreated(String sourceHost, int port, String blobId, BlobReplicaSourceType sourceType) { int numberOfReplicas; try { BlobId blobIdObj = new BlobId(blobId, clusterMap); PartitionId partitionId = blobIdObj.getPartition(); numberOfReplicas = partitionId.getReplicaIds().size(); } catch (Exception e) { <START> throw new IllegalArgumentException("Invalid blob ID: " + blobId); <END> } objectTracker.computeIfAbsent(blobId, k -> new Tracker(numberOfReplicas)).trackCreation(sourceHost, port); }</code><technical_language>pass in exception too</technical_language>

Target:
public synchronized void onBlobReplicaCreated(String sourceHost, int port, String blobId, BlobReplicaSourceType sourceType) { int numberOfReplicas; try { BlobId blobIdObj = new BlobId(blobId, clusterMap); PartitionId partitionId = blobIdObj.getPartition(); numberOfReplicas = partitionId.getReplicaIds().size(); } catch (Exception e) { throw new IllegalArgumentException("Invalid blob ID: " + blobId, e); } objectTracker.computeIfAbsent(blobId, k -> new Tracker(numberOfReplicas)).trackCreation(sourceHost, port); }
Source:
<code><START> int getNumDataChunks() { <END> return chunksToStitch != null ? chunksToStitch.size() : RouterUtils.getNumChunksForBlobAndChunkSize(getBlobSize(), routerConfig.routerMaxPutChunkSizeBytes); }</code><technical_language>this IllegalStateException removed? exception is thrown out of this method</technical_language>

Target:
int getNumDataChunks() { return isStitchOperation() ? chunksToStitch.size() : RouterUtils.getNumChunksForBlobAndChunkSize(getBlobSize(), routerConfig.routerMaxPutChunkSizeBytes); }
Source:
<code>public void testExectueQuery() { DbFacade dbFacadeMock = mock(DbFacade.class); mockStatic(DbFacade.class); when(DbFacade.getInstance()).thenReturn(dbFacadeMock); VmNetworkInterfaceDAO daoMock = mock(VmNetworkInterfaceDAO.class); when(dbFacadeMock.getVmNetworkInterfaceDAO()).thenReturn(daoMock); Guid guid = new Guid(); Guid userID = new Guid(); IVdcUser user = mock(IVdcUser.class); when(user.getUserId()).thenReturn(userID); <START> GetVmByVmIdParameters params = mock(GetVmByVmIdParameters.class); <END> when(params.getId()).thenReturn(guid); when(params.isFiltered()).thenReturn(true); GetVmInterfacesByVmIdQuery query = spy(new GetVmInterfacesByVmIdQuery(params)); when(query.getUser()).thenReturn(user); query.executeQueryCommand(); verify(daoMock, times(1)).getAllForVm(guid, userID, true); }</code><technical_language>this overuse of mocking abilities? Parameters POJOs, need mock them.</technical_language>

Target:
public void testExectueQuery() { DbFacade dbFacadeMock = mock(DbFacade.class); mockStatic(DbFacade.class); when(DbFacade.getInstance()).thenReturn(dbFacadeMock); VmNetworkInterfaceDAO daoMock = mock(VmNetworkInterfaceDAO.class); when(dbFacadeMock.getVmNetworkInterfaceDAO()).thenReturn(daoMock); Guid guid = new Guid(); Guid userID = new Guid(); IVdcUser user = mock(IVdcUser.class); when(user.getUserId()).thenReturn(userID); GetVmByVmIdParameters params = mock(GetVmByVmIdParameters.class); when(params.getId()).thenReturn(guid); when(params.isFiltered()).thenReturn(true); GetVmInterfacesByVmIdQuery query = spy(new GetVmInterfacesByVmIdQuery(params)); when(query.getUser()).thenReturn(user); query.executeQueryCommand(); verify(daoMock).getAllForVm(guid, userID, true); }
Source:
<code><START> protected void show() { <END> if (TextUtils.isEmpty(placementName)) { IronSource.showRewardedVideo(); } else { IronSource.showRewardedVideo(placementName); } }</code><technical_language>@artemkuzmenko Extend CustomEventRewardedVideo override showVideo() instead of show()</technical_language>

Target:
protected void show() { if (TextUtils.isEmpty(mPlacementName)) { IronSource.showISDemandOnlyRewardedVideo(mInstanceId); } else { IronSource.showISDemandOnlyRewardedVideo(mInstanceId,mPlacementName); } }