auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setUp() throws Exception { ca = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("ca-cert.pem")); cert = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("cert.pem")); certEmbedded = OpenSSLX509Certificate.fromX509PemInputStream( openTestFile("cert-ct-embedded.pem")); PublicKey key = OpenSSLKey.fromPublicKeyPemInputStream( openTestFile("ct-server-key-public.pem")).getPublicKey(); <START> <END> final CTLogInfo log = new CTLogInfo(key, "Test Log", "foo"); CTLogStore store = new CTLogStore() { public CTLogInfo getKnownLog(byte[] logId) { if (Arrays.equals(logId, log.getID())) { return log; } else { return null; } } }; ctVerifier = new CTVerifier(store); }</code><technical_language>whitespace in empty line, please remove</technical_language>

Target:
public void setUp() throws Exception { ca = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("ca-cert.pem")); cert = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("cert.pem")); certEmbedded = OpenSSLX509Certificate.fromX509PemInputStream( openTestFile("cert-ct-embedded.pem")); PublicKey key = OpenSSLKey.fromPublicKeyPemInputStream( openTestFile("ct-server-key-public.pem")).getPublicKey(); CTLogStore store = new CTLogStoreImpl(new CTLogInfo[] { new CTLogInfo(key, "Test Log", "foo") }); ctVerifier = new CTVerifier(store); }
Source:
<code><START> protected ImportOp getImportOp(DataStore dataStore) { <END> final ImportOp importOp = context.command(ImportOp.class); return importOp.setDataStore(dataStore).setTable(table).setAll(all).setOverwrite(!add) .setAdaptToDefaultFeatureType(!forceFeatureType).setAlter(alter) .setDestinationPath(dest).setFidAttribute(fidAttribute); }</code><technical_language>this method protected getters lead this class is extended methods accessible/override-able subclass. case. remove getters getImportOp private</technical_language>

Target:
private ImportOp getImportOp(DataStore dataStore) { final ImportOp importOp = context.command(ImportOp.class); return importOp.setDataStore(dataStore).setTable(table).setAll(all).setOverwrite(!add) .setAdaptToDefaultFeatureType(!forceFeatureType).setAlter(alter) .setDestinationPath(dest).setFidAttribute(fidAttribute); }
Source:
<code><START> public String rewrite(Configuration conf, String query) throws GrillException { <END> this.query = query; this.conf = conf; try { if (query.toLowerCase().matches("(.*)union all(.*)")) { String[] queries = query.toLowerCase().split("union all"); for (int i = 0; i < queries.length; i++) { ast = HQLParser.parseHQL(queries[i]); buildQuery(); mergedQuery = rewrittenQuery.append(" union all "); finalRewrittenQuery = mergedQuery.toString().substring(0, mergedQuery.lastIndexOf("union all")); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + finalRewrittenQuery); reset(); } } else { ast = HQLParser.parseHQL(query); buildQuery(); finalRewrittenQuery = rewrittenQuery.toString(); } } catch (ParseException e) { e.printStackTrace(); } return finalRewrittenQuery; }</code><technical_language>this method synchronized rewriter instance is shared multiple threads in jdbc driver</technical_language>

Target:
public synchronized String rewrite(Configuration conf, String query) throws GrillException { this.query = query; this.conf = conf; try { if (query.toLowerCase().matches("(.*)union all(.*)")) { String[] queries = query.toLowerCase().split("union all"); for (int i = 0; i < queries.length; i++) { ast = HQLParser.parseHQL(queries[i]); buildQuery(); mergedQuery = rewrittenQuery.append(" union all "); finalRewrittenQuery = mergedQuery.toString().substring(0, mergedQuery.lastIndexOf("union all")); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + finalRewrittenQuery); reset(); } } else { ast = HQLParser.parseHQL(query); buildQuery(); finalRewrittenQuery = rewrittenQuery.toString(); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + finalRewrittenQuery); } } catch (ParseException e) { e.printStackTrace(); } return finalRewrittenQuery; }
Source:
<code>private CswRecordCollection queryProductById(String id, String rangeValue) throws CswException, UnsupportedQueryException { final ResourceRequestById resourceRequest = new ResourceRequestById(id); long bytesToSkip = getRange(rangeValue); if (bytesToSkip > 0) { if (LOGGER.isDebugEnabled()) { <START> LOGGER.debug("Bytes to skip: {}", String.valueOf(bytesToSkip)); <END> } resourceRequest.getProperties().put(CswConstants.BYTES_TO_SKIP, bytesToSkip); } ResourceResponse resourceResponse; try { resourceResponse = framework.getLocalResource(resourceRequest); } catch (IOException | ResourceNotFoundException | ResourceNotSupportedException e) { throw new CswException(String.format(ERROR_ID_PRODUCT_RETRIEVAL, id), e); } Resource resource = resourceResponse.getResource(); MimeType mimeType = resource.getMimeType(); if (mimeType == null) { try { mimeType = new MimeType(MediaType.APPLICATION_OCTET_STREAM); resource = new ResourceImpl(resource.getInputStream(), mimeType, resource.getName()); } catch (MimeTypeParseException e) { throw new CswException( String.format( "Could not create mime type upon null mimeType, for mime %s.", MediaType.APPLICATION_OCTET_STREAM), e); } } CswRecordCollection cswRecordCollection = new CswRecordCollection(); cswRecordCollection.setResource(resource); cswRecordCollection.setOutputSchema(OCTET_STREAM_OUTPUT_SCHEMA); LOGGER.debug("{} successfully retrieved product for ID: {}", id); return cswRecordCollection; }</code><technical_language>convert bytesToSkip a string String.valueOf()? pass bytesToSkip is avoid if altogether</technical_language>

Target:
private CswRecordCollection queryProductById(String id, String rangeValue) throws CswException, UnsupportedQueryException { final ResourceRequestById resourceRequest = new ResourceRequestById(id); long bytesToSkip = getRange(rangeValue); if (bytesToSkip > 0) { LOGGER.debug("Bytes to skip: {}", bytesToSkip); resourceRequest.getProperties().put(CswConstants.BYTES_TO_SKIP, bytesToSkip); } ResourceResponse resourceResponse; try { resourceResponse = framework.getLocalResource(resourceRequest); } catch (IOException | ResourceNotFoundException | ResourceNotSupportedException e) { throw new CswException(String.format(ERROR_ID_PRODUCT_RETRIEVAL, id), e); } Resource resource = resourceResponse.getResource(); MimeType mimeType = resource.getMimeType(); if (mimeType == null) { try { mimeType = new MimeType(MediaType.APPLICATION_OCTET_STREAM); resource = new ResourceImpl(resource.getInputStream(), mimeType, resource.getName()); } catch (MimeTypeParseException e) { throw new CswException( String.format( "Could not create mime type upon null mimeType, for mime %s.", MediaType.APPLICATION_OCTET_STREAM), e); } } CswRecordCollection cswRecordCollection = new CswRecordCollection(); cswRecordCollection.setResource(resource); cswRecordCollection.setOutputSchema(OCTET_STREAM_OUTPUT_SCHEMA); LOGGER.debug("{} successfully retrieved product for ID: {}", id); return cswRecordCollection; }
Source:
<code>private void tryRemoveOnlineUseCases(@NonNull Collection<UseCase> toRemove) { List<UseCase> useCasesChangedToOffline = new ArrayList<>(); for (UseCase useCase : toRemove) { if (mUseCaseAttachState.isUseCaseOnline(useCase)) { mUseCaseAttachState.setUseCaseOffline(useCase); useCasesChangedToOffline.add(useCase); } } if (useCasesChangedToOffline.isEmpty()) { return; } Log.d(TAG, "Use cases [" + TextUtils.join(", ", useCasesChangedToOffline) + "] now OFFLINE for camera " + mCameraInfoInternal.getCameraId()); clearCameraControlPreviewAspectRatio(useCasesChangedToOffline); notifyStateOfflineToUseCases(useCasesChangedToOffline); boolean allUseCasesOffline = mUseCaseAttachState.getOnlineUseCases().isEmpty(); if (allUseCasesOffline) { mCameraControlInternal.setActive(false); resetCaptureSession( false); <START> mCaptureSession.setSessionConfig(null); <END> closeInternal(); } else { updateCaptureSessionConfig(); resetCaptureSession( false); if (mState == InternalState.OPENED) { openCaptureSession(); } } }</code><technical_language>This is OK case active state (the changes in UseCaseAttachState remove case active state offline). resuming, updateCaptureSessionConfig able get "active" case recreate CameraCaptureSession</technical_language>

Target:
private void tryRemoveOnlineUseCases(@NonNull Collection<UseCase> toRemove) { List<UseCase> useCasesChangedToOffline = new ArrayList<>(); for (UseCase useCase : toRemove) { if (mUseCaseAttachState.isUseCaseOnline(useCase)) { mUseCaseAttachState.setUseCaseOffline(useCase); useCasesChangedToOffline.add(useCase); } } if (useCasesChangedToOffline.isEmpty()) { return; } Log.d(TAG, "Use cases [" + TextUtils.join(", ", useCasesChangedToOffline) + "] now OFFLINE for camera " + mCameraInfoInternal.getCameraId()); clearCameraControlPreviewAspectRatio(useCasesChangedToOffline); notifyStateOfflineToUseCases(useCasesChangedToOffline); boolean allUseCasesOffline = mUseCaseAttachState.getOnlineUseCases().isEmpty(); if (allUseCasesOffline) { mCameraControlInternal.setActive(false); resetCaptureSession( false); mCaptureSession = mCaptureSessionBuilder.build(); closeInternal(); } else { updateCaptureSessionConfig(); resetCaptureSession( false); if (mState == InternalState.OPENED) { openCaptureSession(); } } }
Source:
<code>public final void convertToHeapBuffer() { if (m_buffer.isDirect()) { <START> ByteBuffer heapBuffer = ByteBuffer.allocate(m_buffer.limit()); <END> m_buffer.position(0); heapBuffer.put(m_buffer); heapBuffer.position(heapBuffer.limit()); } }</code><technical_language>This is a nit, this "can reuse buffer FOR next stored procedure"</technical_language>

Target:
public final void convertToHeapBuffer() { if (m_buffer.isDirect()) { ByteBuffer heapBuffer = ByteBuffer.allocate(m_buffer.limit()); m_buffer.position(0); heapBuffer.put(m_buffer); m_buffer = heapBuffer; } }
Source:
<code>protected void convertEAttribute(SIRIUS siriusEObject, EObject eefEObject, EAttribute eAttribute, Map<String, Object> parameters) { EStructuralFeature eefEStructuralFeature = eefEObject.eClass().getEStructuralFeature(eAttribute.getName()); if (eefEStructuralFeature instanceof EAttribute) { if (eefEStructuralFeature.getEType().getInstanceClass().equals(eAttribute.getEType().getInstanceClass())) { eefEObject.eSet(eefEStructuralFeature, siriusEObject.eGet(eAttribute)); } else if (eefEStructuralFeature.getEType().equals(EcorePackage.Literals.EINT) && eAttribute.getEType().equals(EcorePackage.Literals.ESTRING)) { Object value = siriusEObject.eGet(eAttribute); eefEObject.eSet(eefEStructuralFeature, Integer.toString(Integer.valueOf(value.toString()))); } } else { eefEStructuralFeature = eefEObject.eClass().getEStructuralFeature("identifier"); if (eAttribute.equals(DescriptionPackage.Literals.IDENTIFIED_ELEMENT__NAME) && eefEStructuralFeature instanceof EAttribute) { eefEObject.eSet(eefEStructuralFeature, <START> siriusEObject.eGet(EefPackage.Literals.EEF_CONTROL_DESCRIPTION__IDENTIFIER)); <END> } } }</code><technical_language>wrong, missing somehting: eGet-ting EEF feature Sirius EObject</technical_language>

Target:
protected void convertEAttribute(SIRIUS siriusEObject, EObject eefEObject, EAttribute eAttribute, Map<String, Object> parameters) { EStructuralFeature eefEStructuralFeature = eefEObject.eClass().getEStructuralFeature(eAttribute.getName()); if (eefEStructuralFeature instanceof EAttribute) { if (eefEStructuralFeature.getEType().getInstanceClass().equals(eAttribute.getEType().getInstanceClass())) { eefEObject.eSet(eefEStructuralFeature, siriusEObject.eGet(eAttribute)); } else if (eefEStructuralFeature.getEType().equals(EcorePackage.Literals.EINT) && eAttribute.getEType().equals(EcorePackage.Literals.ESTRING)) { Object value = siriusEObject.eGet(eAttribute); eefEObject.eSet(eefEStructuralFeature, Integer.toString(Integer.valueOf(value.toString()))); } } else { eefEStructuralFeature = eefEObject.eClass().getEStructuralFeature("identifier"); if (eAttribute.equals(DescriptionPackage.Literals.IDENTIFIED_ELEMENT__NAME) && eefEStructuralFeature instanceof EAttribute) { eefEObject.eSet(eefEStructuralFeature, siriusEObject.eGet(DescriptionPackage.Literals.IDENTIFIED_ELEMENT__NAME)); } } }
Source:
<code>public void testConnectTimeout() throws Exception { PowerMockito.doThrow(new XBeeException(XBeeException.CONNECTION_TIMEOUT)).when(xbeeDevice, "connect"); try { xbeeDevice.connect(); fail("Device shouldn't have connected"); } catch (XBeeException e) { } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } <START> assertEquals(xbeeDevice.getOperatingMode(), XBeeMode.UNKNOWN); <END> }</code><technical_language>Verify device is connected here</technical_language>

Target:
public void testConnectTimeout() throws Exception { PowerMockito.doThrow(new XBeeException(XBeeException.CONNECTION_TIMEOUT)).when(xbeeDevice, "open"); try { xbeeDevice.open(); fail("Device shouldn't have connected"); } catch (XBeeException e) { } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } assertFalse(xbeeDevice.isOpen()); assertFalse(dataReader.isRunning()); assertEquals(xbeeDevice.getOperatingMode(), OperatingMode.UNKNOWN); }
Source:
<code>private static byte[] createRequestBody(String query, DruidResultFormat resultFormat, boolean queryHeader) { return format("{\"query\":\"%s\",\"resultFormat" + <START> "\":\"%s\",\"header\": %b }\n", query, resultFormat.getResultFormat(), queryHeader).getBytes(); <END> }</code><technical_language>line, instead of splitting 2 lines</technical_language>

Target:
private static byte[] createRequestBody(String query, DruidResultFormat resultFormat, boolean queryHeader) { return format("{\"query\":\"%s\",\"resultFormat\":\"%s\",\"header\": %b }\n", query, resultFormat.getResultFormat(), queryHeader).getBytes(); }
Source:
<code>public void bindChildView(View view, Context context, Cursor cursor, boolean isLastChild) { final EpisodeViewHolder viewHolder = (EpisodeViewHolder)view.getTag(); viewHolder.episodeId = cursor.getInt(EpisodesListQuery.EPISODEID); viewHolder.episodenumberView.setText( String.format(context.getString(R.string.episode_number), cursor.getInt(EpisodesListQuery.EPISODE))); int runtime = cursor.getInt(EpisodesListQuery.RUNTIME) / 60; String duration = runtime > 0 ? String.format(context.getString(R.string.minutes_abbrev), String.valueOf(runtime)) + " | " + cursor.getString(EpisodesListQuery.FIRSTAIRED) : cursor.getString(EpisodesListQuery.FIRSTAIRED); viewHolder.titleView.setText(cursor.getString(EpisodesListQuery.TITLE)); viewHolder.detailsView.setText(duration); if (cursor.getInt(EpisodesListQuery.PLAYCOUNT) > 0) { viewHolder.episodenumberView.setTextColor(themeAccentColor); viewHolder.titleView.setTextColor(themeAccentColor); viewHolder.contextMenuView.setColorFilter(themeAccentColor); } else { viewHolder.episodenumberView.setTextColor(defaultTextColor); viewHolder.titleView.setTextColor(defaultTextColor); viewHolder.contextMenuView.setColorFilter(themeAccentColor); <START> viewHolder.contextMenuView.clearColorFilter(); <END> } ImageView contextMenu = (ImageView)view.findViewById(R.id.list_context_menu); contextMenu.setTag(viewHolder); contextMenu.setOnClickListener(contextlistItemMenuClickListener); }</code><technical_language>reason for setting color filter clearing it</technical_language>

Target:
public void bindChildView(View view, Context context, Cursor cursor, boolean isLastChild) { final EpisodeViewHolder viewHolder = (EpisodeViewHolder)view.getTag(); viewHolder.episodeId = cursor.getInt(EpisodesListQuery.EPISODEID); viewHolder.episodenumberView.setText( String.format(context.getString(R.string.episode_number), cursor.getInt(EpisodesListQuery.EPISODE))); int runtime = cursor.getInt(EpisodesListQuery.RUNTIME) / 60; String duration = runtime > 0 ? String.format(context.getString(R.string.minutes_abbrev), String.valueOf(runtime)) + " | " + cursor.getString(EpisodesListQuery.FIRSTAIRED) : cursor.getString(EpisodesListQuery.FIRSTAIRED); viewHolder.titleView.setText(cursor.getString(EpisodesListQuery.TITLE)); viewHolder.detailsView.setText(duration); if (cursor.getInt(EpisodesListQuery.PLAYCOUNT) > 0) { viewHolder.checkmarkView.setVisibility(View.VISIBLE); viewHolder.checkmarkView.setColorFilter(themeAccentColor); } else { viewHolder.checkmarkView.setVisibility(View.INVISIBLE); } ImageView contextMenu = (ImageView)view.findViewById(R.id.list_context_menu); contextMenu.setTag(viewHolder); contextMenu.setOnClickListener(contextlistItemMenuClickListener); }
Source:
<code><START> public @NonNull String eventKmemPageAlloc() { <END> return "kmem:page_alloc"; }</code><technical_language>do need @NonNull</technical_language>

Target:
public String eventKmemPageAlloc() { return "kmem:page_alloc"; }
Source:
<code>public void run( Parameters params, TopNResultBuilder resultBuilder, DimValSelector dimValSelector ) { boolean hasDimValSelector = (dimValSelector != null); <START> int cardinality = params.getCardinality(); <END> if (cardinality < 0) { cardinality = Integer.MAX_VALUE; } int numProcessed = 0; while (numProcessed < cardinality) { final int numToProcess; int maxNumToProcess = Math.min(params.getNumValuesPerPass(), cardinality - numProcessed); DimValSelector theDimValSelector; if (!hasDimValSelector) { numToProcess = maxNumToProcess; theDimValSelector = makeDimValSelector(params, numProcessed, numToProcess); } else { numToProcess = computeNewLength(dimValSelector, numProcessed, maxNumToProcess); theDimValSelector = updateDimValSelector(dimValSelector, numProcessed, numToProcess); } DimValAggregateStore aggregatesStore = makeDimValAggregateStore(params); scanAndAggregate(params, theDimValSelector, aggregatesStore, numProcessed); updateResults(params, theDimValSelector, aggregatesStore, resultBuilder); closeAggregators(aggregatesStore); numProcessed += numToProcess; params.getCursor().reset(); } }</code><technical_language>this change a part of this PR? cardinality < 0 means completely approach compute topN, setting Integer.MAX_VALUE result in a lot of excessive work allocations in run() method</technical_language>

Target:
public void run( Parameters params, TopNResultBuilder resultBuilder, DimValSelector dimValSelector ) { if (params.getCardinality() != TopNColumnSelectorStrategy.CARDINALITY_UNKNOWN) { runWithCardinalityKnown(params, resultBuilder, dimValSelector); } else { runWithCardinalityUnknown(params, resultBuilder); } }
Source:
<code>public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { configuration.setAttribute(ILaunchConstants.ATTR_ADDITIONAL_DIRS, (String) null); configuration.setAttribute(ILaunchConstants.ATTR_CONNECTION_URI, ""); Preferences prefs = InstanceScope.INSTANCE <START> .getNode(org.eclipse.linuxtools.docker.ui.Activator.PLUGIN_ID); <END> String image = prefs.get(PreferenceConstants.DEFAULT_IMAGE, ""); configuration.setAttribute(ILaunchConstants.ATTR_IMAGE, image); Preferences prefs2 = InstanceScope.INSTANCE .getNode(DockerLaunchUIPlugin.PLUGIN_ID); Boolean keepContainer = prefs2.getBoolean( PreferenceConstants.KEEP_CONTAINER_AFTER_LAUNCH, false); configuration.setAttribute(ILaunchConstants.ATTR_KEEP_AFTER_LAUNCH, keepContainer); configuration.setAttribute(ILaunchConstants.ATTR_STDIN_SUPPORT, false); }</code><technical_language>This is strange. preference store of Linux Tools Docker plugin fetching ID is defined in CDT? I prefStore DockerLaunchUIPlugin, no</technical_language>

Target:
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { configuration.setAttribute(ILaunchConstants.ATTR_ADDITIONAL_DIRS, (String) null); configuration.setAttribute(ILaunchConstants.ATTR_CONNECTION_URI, ""); Preferences prefs = InstanceScope.INSTANCE .getNode(DockerLaunchUIPlugin.PLUGIN_ID); String image = prefs.get(PreferenceConstants.DEFAULT_IMAGE, ""); configuration.setAttribute(ILaunchConstants.ATTR_IMAGE, image); Boolean keepContainer = prefs.getBoolean( PreferenceConstants.KEEP_CONTAINER_AFTER_LAUNCH, false); configuration.setAttribute(ILaunchConstants.ATTR_KEEP_AFTER_LAUNCH, keepContainer); configuration.setAttribute(ILaunchConstants.ATTR_STDIN_SUPPORT, false); }
Source:
<code>private void initLMPreparationHandler() { if (lmPreparationHandler.hasLMProfiles()) return; for (LMProfileConfig lmConfig : lmPreparationHandler.getLMProfileConfigs()) { ProfileConfig profile = profilesByName.get(lmConfig.getProfile()); <START> Weighting weighting = createWeighting(profile, new PMap().put("__disable_turn_costs", true)); <END> lmPreparationHandler.addLMProfile(new LMProfile(profile.getName(), weighting)); } }</code><technical_language>I do this force usage of turn cost provider in LM. IMO this is implementation specific</technical_language>

Target:
private void initLMPreparationHandler() { if (lmPreparationHandler.hasLMProfiles()) return; for (LMProfileConfig lmConfig : lmPreparationHandler.getLMProfileConfigs()) { ProfileConfig profile = profilesByName.get(lmConfig.getProfile()); Weighting weighting = createWeighting(profile, new PMap()); lmPreparationHandler.addLMProfile(new LMProfile(profile.getName(), weighting)); } }
Source:
<code>public void testFinalizerInvoked() throws InterruptedException { BasicTask<?> t = new BasicTask<Void>(new Runnable() { public void run() { }}); final int[] x = new int[1]; t.setFinalizer(new BasicTask.TaskFinalizer() { public void onTaskFinalization(Task<?> t) { synchronized (x) { x[0]++; x.notifyAll(); } } }); t = null; System.gc(); System.gc(); synchronized (x) { <START> if (x[0]==1) return; <END> x.wait(5*1000); if (x[0]==1) return; } Assert.fail("finalizer did not run in time"); }</code><technical_language>Asserts.succeedsEventually(new Runnable() { public void run() {assertEquals(x[0], 1); } }); avoid waiting 5000ms 1ms done</technical_language>

Target:
public void testFinalizerInvoked() throws InterruptedException { BasicTask<?> t = new BasicTask<Void>(new Runnable() { public void run() { }}); final Semaphore x = new Semaphore(0); t.setFinalizer(new BasicTask.TaskFinalizer() { public void onTaskFinalization(Task<?> t) { synchronized (x) { x.release(); } } }); t = null; Stopwatch watch = new Stopwatch().start(); for (int i=0; i<30; i++) { System.gc(); System.gc(); if (x.tryAcquire(1, TimeUnit.SECONDS)) { log.info("finalizer ran after "+Time.makeTimeStringRounded(watch)); return; } } Assert.fail("finalizer did not run in time"); }
Source:
<code>public boolean validateCert(X509Certificate certToCheck) { String leafIssuerString = certToCheck.getIssuerX500Principal().getName(); LOG.debug("Issue Name for validated Cert {}", leafIssuerString); List<X509Certificate> allCerts = getAllCertByIssuer(certificateManager.getTrustStore(), leafIssuerString); if (isPartChainOfTrust(certToCheck)) { LOG.debug("Cert serial number to verify against our trustStore {}", <START> certToCheck.getSerialNumber().toString(16)); <END> String authorityKeyIdentifier = getAuthorityKeyIdentify(certToCheck.getExtensionValue(AUTHORITY_KEY_ID)); for (X509Certificate cert : allCerts) { String subjectKeyId = getSubjectKeyID(cert.getExtensionValue(SUBJECT_KEY_ID)); if (StringUtils.isNotBlank(subjectKeyId) && StringUtils.isNotBlank(authorityKeyIdentifier) && subjectKeyId.equalsIgnoreCase(authorityKeyIdentifier)) { LOG.debug("Found the match with cert serial number{} ", cert.getSerialNumber().toString(16)); return validateCert(cert); } } } else { LOG.debug("This cert is either self-sign cert or root CA"); for (X509Certificate cert : allCerts) { if (cert.equals(certToCheck)) { LOG.debug("Found the cert in trust store with serial number {}", cert.getSerialNumber() .toString(16)); return true; } } return false; } return false; }</code><technical_language>BASE16 constant .. 16 is vague</technical_language>

Target:
public boolean validateCert(X509Certificate certToCheck) { String leafIssuerString = certToCheck.getIssuerX500Principal().getName(); LOG.debug("Issue Name for validated Cert " + leafIssuerString); List<X509Certificate> allCerts = getAllCertByIssuer(certificateManager.getTrustStore(), leafIssuerString); if (isPartChainOfTrust(certToCheck)) { LOG.debug("Cert serial number to verify against our trustStore " + getCertSerialNumber(certToCheck)); String authorityKeyIdentifier = getAuthorityKeyIdentify(certToCheck.getExtensionValue(AUTHORITY_KEY_ID)); for (X509Certificate cert : allCerts) { String subjectKeyId = getSubjectKeyID(cert.getExtensionValue(SUBJECT_KEY_ID)); if (StringUtils.isNotBlank(subjectKeyId) && StringUtils.isNotBlank(authorityKeyIdentifier) && subjectKeyId.equalsIgnoreCase(authorityKeyIdentifier)) { LOG.debug("Found the match with cert serial number " + getCertSerialNumber(cert)); return validateCert(cert); } } } else { LOG.debug("This cert is either self-sign cert or root CA"); for (X509Certificate cert : allCerts) { if (cert.equals(certToCheck)) { LOG.debug("Found the cert in trust store with serial number " + getCertSerialNumber(cert)); return true; } } return false; } return false; }
Source:
<code>private void promptForDockerHostIfMissing(DockerHelper dockerHelper, String dockerHost) { if (StringUtils.isBlank(dockerHelper.getDockerHost())) { String host = null; if(SystemUtils.IS_OS_LINUX){ host = promptForValueIfMissingWithDefault("Please specify Docker host URL (either 'tcp://' or 'unix://')", dockerHost, "dockerHost", ""); } else if (SystemUtils.IS_OS_WINDOWS){ showMessage("Checking default Windows Docker host addresses:"); showMessage("Checking \"Docker for Windows\""); if (isDefaultDockerForWindowsPresent()) { host = DockerHelper.DEFAULT_HOST_DOCKER_FOR_WINDOWS; } else { showMessage("Checking \"Docker Toolbox\""); String dockerToolboxHost = getDefaultDockerToolboxHost(); if (dockerToolboxHost != null) { host = dockerToolboxHost; } } if (host == null) { showMessage("Docker Host URL is needed in order to connect to your Docker instance."); host = promptForValueIfMissingWithDefault("Please specify Docker host URL", host, "dockerHost", ""); } } else if (SystemUtils.IS_OS_MAC_OSX) { showMessage("Checking default Docker for Mac host address:"); if (isDefaultDockerForMacPresent()) { host = DockerHelper.DEFAULT_HOST_DOCKER_FOR_MAC; <START> } <END> else { showMessage("Docker Host URL is needed in order to connect to your Docker instance."); host = promptForValueIfMissingWithDefault( "Please specify Docker host URL", dockerHelper.getDockerHost(), "dockerHost", ""); } } dockerHelper.saveDockerHost(host); } }</code><technical_language>Docker For Mac unix:///var/run/docker.sock Check 'docker-machine url' first. returns "Host is running" in Docker For Mac. unix://var/run/docker.sock default</technical_language>

Target:
private void promptForDockerHostIfMissing(DockerHelper dockerHelper, String dockerHost) { if (StringUtils.isNotEmpty(dockerHost)) { if (dockerHost.equals("true")) { showMessage("Attempting to find default docker host address..."); dockerHelper.saveDockerHost(getDefaultDockerHost()); } else { dockerHelper.saveDockerHost(dockerHost); } } else if (StringUtils.isBlank(dockerHelper.getDockerHost())) { showMessage("-DdockerHost is not specified in batch mode. Attempting to find default docker host address..."); dockerHelper.saveDockerHost(getDefaultDockerHost()); } }
Source:
<code>public void setGameInfoBean(GameInfoBean gameInfoBean) { mapPreview.setImage(mapService.loadSmallPreview(gameInfoBean.getMapTechnicalName())); MapInfoBean mapInfoBean = mapService.getMapInfoBeanFromVaultFromName(gameInfoBean.getMapTechnicalName()); if (gameInfoBean.getTeams().size() > 1) { gameTitleLabel.setText(i18n.get("chat.gameStatus.gameTitle", gameInfoBean.getTitle())); try { mapNameLabel.setText(i18n.get("chat.gameStatus.mapName", mapInfoBean.getDisplayName())); <START> } catch (NullPointerException e) { <END> } featuredModLabel.setText(i18n.get("chat.gameStatus.featuredMod", gameInfoBean.getFeaturedMod())); } else { gameTitleLabel.setText(gameInfoBean.getTitle()); try { mapNameLabel.setText(mapInfoBean.getDisplayName()); } catch (NullPointerException e) { } featuredModLabel.setText(gameInfoBean.getFeaturedMod()); } GameTooltipController gameTooltipController = applicationContext.getBean(GameTooltipController.class); gameTooltipController.setGameInfoBean(gameInfoBean); gameStatusTooltipRoot.getChildren().add(gameTooltipController.getRoot()); }</code><technical_language>catch NPEs, check for null instead</technical_language>

Target:
public void setGameInfoBean(GameInfoBean gameInfoBean) { mapPreview.setImage(mapService.loadSmallPreview(gameInfoBean.getMapTechnicalName())); MapInfoBean mapInfoBean = mapService.getMapInfoBeanFromVaultByName(gameInfoBean.getMapTechnicalName()); gameTitleLabel.setText(i18n.get("chat.gameStatus.gameTitle", gameInfoBean.getTitle())); featuredModLabel.setText(i18n.get("chat.gameStatus.featuredMod", gameInfoBean.getFeaturedMod())); if (mapInfoBean != null) { mapNameLabel.setText(i18n.get("chat.gameStatus.mapName", mapInfoBean.getDisplayName())); } GameTooltipController gameTooltipController = applicationContext.getBean(GameTooltipController.class); gameTooltipController.setGameInfoBean(gameInfoBean); gameStatusTooltipRoot.getChildren().add(gameTooltipController.getRoot()); gameStatusTooltipRoot.getChildren(); }
Source:
<code>private void updateQuota(Guid storageDomainId, final ListModel<Quota> isItem, final Guid diskQuotaId) { if (getQuotaEnforcementType() != QuotaEnforcementTypeEnum.DISABLED && storageDomainId != null) { AsyncDataProvider.getInstance().getAllRelevantQuotasForStorageSorted(new AsyncQuery<>( list -> { if (list == null) { return; } Guid selectedQuota = <START> isItem.getSelectedItem() <END> != null ? isItem.getSelectedItem().getId() : diskQuotaId; isItem.setItems(list); if (selectedQuota != null && list.size() > 1) { for (Quota quota : list) { if (quota.getId().equals(selectedQuota)) { isItem.setSelectedItem(quota); break; } } } }), storageDomainId, null); } }</code><technical_language>original code "isItem" null fail here. "isItem" is null here</technical_language>

Target:
private void updateQuota(Guid storageDomainId, final ListModel<Quota> isItem, final Guid diskQuotaId) { if (getQuotaEnforcementType() != QuotaEnforcementTypeEnum.DISABLED && storageDomainId != null) { AsyncDataProvider.getInstance().getAllRelevantQuotasForStorageSorted(new AsyncQuery<>( list -> { if (list == null) { return; } Guid selectedQuota = isItem.getSelectedItem() != null ? isItem.getSelectedItem().getId() : null; selectedQuota = selectedQuota != null ? selectedQuota : diskQuotaId; isItem.setItems(list); if (selectedQuota != null && list.size() > 1) { for (Quota quota : list) { if (quota.getId().equals(selectedQuota)) { isItem.setSelectedItem(quota); break; } } } }), storageDomainId, null); } }
Source:
<code>public InstructorCourseStudentDetailsPageData(AccountAttributes account, StudentAttributes student, StudentProfileAttributes studentProfile, boolean isAbleToAddComment, boolean hasSection, String commentRecipient) { super(account); if (studentProfile != null) { String pictureUrl = studentProfile.pictureKey == null || studentProfile.pictureKey.isEmpty() ? Const.SystemParams.DEFAULT_PROFILE_PICTURE_PATH : Const.ActionURIs.STUDENT_PROFILE_PICTURE + "?" + Const.ParamsNames.BLOB_KEY + "=" + studentProfile.pictureKey + "&" + Const.ParamsNames.USER_ID + "=" + account.googleId; <START> this.studentProfile = new StudentProfile(student.name, studentProfile, pictureUrl); <END> } this.studentInfoTable = new StudentInfoTable(student, isAbleToAddComment, hasSection); this.commentRecipient = commentRecipient; }</code><technical_language>A small request: abstract pictureUrl algorithm PageData? This is in StudentProfilePage well</technical_language>

Target:
public InstructorCourseStudentDetailsPageData(AccountAttributes account, StudentAttributes student, StudentProfileAttributes studentProfile, boolean isAbleToAddComment, boolean hasSection, String commentRecipient) { super(account); if (studentProfile != null) { String pictureUrl = getPictureUrl(studentProfile.pictureKey); this.studentProfile = new StudentProfile(student.name, studentProfile, pictureUrl); } this.studentInfoTable = new StudentInfoTable(student, isAbleToAddComment, hasSection); this.commentRecipient = commentRecipient; }
Source:
<code>void insert(GroupInfo info) { Comparator<GroupInfo> c = new Comparator<GroupInfo>() { @Override public int compare(GroupInfo a, GroupInfo b) { int cmp = nullToEmpty(a.name()).compareTo(nullToEmpty(b.name())); if (cmp != 0) { return cmp; } return a.getGroupUUID().compareTo(b.getGroupUUID()); } public String nullToEmpty(String str) { return str == null ? "" : str; } }; int insertPosition = table.getRowCount(); <START> int left = 0; <END> int right = table.getRowCount() - 1; while (left <= right) { int middle = (left + right) >>> 1; GroupInfo i = getRowItem(middle); int cmp = c.compare(i, info); if (cmp < 0) { left = middle + 1; } else if (cmp > 0) { right = middle - 1; } else { return; } } insertPosition = left; table.insertRow(insertPosition); applyDataRowStyle(insertPosition); populate(insertPosition, info); }</code><technical_language>start 1 in previous change. row index 0 is table header</technical_language>

Target:
void insert(GroupInfo info) { Comparator<GroupInfo> c = new Comparator<GroupInfo>() { @Override public int compare(GroupInfo a, GroupInfo b) { int cmp = nullToEmpty(a.name()).compareTo(nullToEmpty(b.name())); if (cmp != 0) { return cmp; } return a.getGroupUUID().compareTo(b.getGroupUUID()); } public String nullToEmpty(String str) { return str == null ? "" : str; } }; int insertPosition = table.getRowCount(); int left = 1; int right = table.getRowCount() - 1; while (left <= right) { int middle = (left + right) / 2; GroupInfo i = getRowItem(middle); int cmp = c.compare(i, info); if (cmp < 0) { left = middle + 1; } else if (cmp > 0) { right = middle - 1; } else { return; } } insertPosition = left; table.insertRow(insertPosition); applyDataRowStyle(insertPosition); populate(insertPosition, info); }
Source:
<code>public Operation<K, V> decode(ByteBuffer buffer) { <START> OperationCode opCode = OperationCode.valueOf(buffer.get()); <END> buffer.rewind(); return opCode.decode(buffer, keySerializer, valueSerializer); }</code><technical_language>This assumes buffer is right place. rewind instead of duplicating? call getOperationCode decode now</technical_language>

Target:
public Operation<K, V> decode(ByteBuffer buffer) { OperationCode opCode = getOperationCode(buffer); return opCode.decode(buffer, keySerializer, valueSerializer); }
Source:
<code>public void <START> testHandleIpConflict() <END> throws Exception { UpstreamNetworkState upstreamNetwork = null; runUsbTethering(upstreamNetwork); final ArgumentCaptor<InterfaceConfigurationParcel> ifaceConfigCaptor = ArgumentCaptor.forClass(InterfaceConfigurationParcel.class); verify(mNetd).interfaceSetCfg(ifaceConfigCaptor.capture()); final String ipv4Address = ifaceConfigCaptor.getValue().ipv4Addr; verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( any(), any()); reset(mNetd, mUsbManager); upstreamNetwork = buildV4WifiUpstreamState(ipv4Address); mTetheringDependencies.mUpstreamNetworkMonitorMasterSM.sendMessage( Tethering.TetherMasterSM.EVENT_UPSTREAM_CALLBACK, UpstreamNetworkMonitor.EVENT_ON_LINKPROPERTIES, 0, upstreamNetwork); mLooper.dispatchAll(); verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_NONE); mTethering.interfaceRemoved(TEST_USB_IFNAME); mLooper.dispatchAll(); verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_RNDIS); }</code><technical_language>This verify if: - is prefix left (for example if upstream changes 192.168.0.0/16) - downstreams conflicting</technical_language>

Target:
public void testHandleIpConflict() throws Exception { UpstreamNetworkState upstreamNetwork = null; runUsbTethering(upstreamNetwork); final ArgumentCaptor<InterfaceConfigurationParcel> ifaceConfigCaptor = ArgumentCaptor.forClass(InterfaceConfigurationParcel.class); verify(mNetd).interfaceSetCfg(ifaceConfigCaptor.capture()); final String ipv4Address = ifaceConfigCaptor.getValue().ipv4Addr; verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks( any(), any()); reset(mNetd, mUsbManager); upstreamNetwork = buildV4WifiUpstreamState(ipv4Address, 30); mTetheringDependencies.mUpstreamNetworkMonitorMasterSM.sendMessage( Tethering.TetherMasterSM.EVENT_UPSTREAM_CALLBACK, UpstreamNetworkMonitor.EVENT_ON_LINKPROPERTIES, 0, upstreamNetwork); mLooper.dispatchAll(); verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_NONE); mTethering.interfaceRemoved(TEST_USB_IFNAME); mLooper.dispatchAll(); verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_RNDIS); }
Source:
<code>private void findMethods(Class<?> entityClass) { for (Method m: entityClass.getMethods()) { <START> InjectLink a = m.getAnnotation(InjectLink.class); <END> Class<?> t = m.getReturnType(); if (a != null) { if (t.equals(String.class) || t.equals(URI.class) || Link.class.isAssignableFrom(t)) { if (!linkMethods.containsKey(m.getName())) { linkMethods.put(m.getName(), new InjectLinkMethodDescriptor(m, a, t)); } } else { } } else if (m.isAnnotationPresent(InjectLinks.class)) { if (List.class.isAssignableFrom(t) || t.isArray() && Link.class.isAssignableFrom(t.getComponentType())) { InjectLinks a2 = m.getAnnotation(InjectLinks.class); linkMethods.put(m.getName(), new InjectLinksMethodDescriptor(m, a2, t)); } else { throw new IllegalArgumentException("Can only inject links onto a List<Link> or Link[] object"); } } else { if(((m.getModifiers() & Modifier.STATIC) > 0) || m.getName().startsWith("java.") || m.getName().startsWith("javax.") ) continue; nonLinkMethods.put(m.getName(), new MethodDescriptor(entityClass, m)); } } }</code><technical_language>create a more general helper method, some common shared code? Basically end of loop, this is identical findFileds (only "output collection"is different), is 100% understandable - findFields, for methods (except need superclasses interfaces). a suggestion, if code readable, leave this (after all, this is in incubator)</technical_language>

Target:
private void findMethods(Class<?> entityClass) { for (Method m: entityClass.getMethods()) { InjectLink a = m.getAnnotation(InjectLink.class); Class<?> t = m.getReturnType(); if (a != null) { if (t.equals(String.class) || t.equals(URI.class) || Link.class.isAssignableFrom(t)) { if (!linkMethods.containsKey(m.getName())) { linkMethods.put(m.getName(), new InjectLinkMethodDescriptor(m, a, t)); } } else { } } else if (m.isAnnotationPresent(InjectLinks.class)) { if (List.class.isAssignableFrom(t) || t.isArray() && Link.class.isAssignableFrom(t.getComponentType())) { InjectLinks a2 = m.getAnnotation(InjectLinks.class); linkMethods.put(m.getName(), new InjectLinksMethodDescriptor(m, a2, t)); } else { throw new IllegalArgumentException("Can only inject links onto method that returns a List<Link> or Link[] object"); } } else { if(((m.getModifiers() & Modifier.STATIC) > 0) || m.getName().startsWith("java.") || m.getName().startsWith("javax.") ) continue; nonLinkMethods.put(m.getName(), new MethodDescriptor(entityClass, m)); } } }
Source:
<code>public void testGetDIOValueSuccess() throws Exception { ATCommandResponse mockedResponse = Mockito.mock(ATCommandResponse.class); Mockito.when(mockedResponse.getResponseStatus()).thenReturn(ATCommandStatus.OK); Mockito.when(mockedResponse.getResponse()).thenReturn(new byte[0]); Mockito.doReturn(mockedResponse).when(xbeeDevice).sendATCommand((ATCommand)Mockito.any()); HashMap<IOLine, IOValue> dioValues = new HashMap<IOLine, IOValue>(); dioValues.put(IOLine.DIO0_AD0, IOValue.HIGH); IOSample mockedIOSample = Mockito.mock(IOSample.class); Mockito.when(mockedIOSample.hasDigitalValues()).thenReturn(true); Mockito.when(mockedIOSample.getDigitalValues()).thenReturn(dioValues); PowerMockito.whenNew(IOSample.class).withAnyArguments().thenReturn(mockedIOSample); IOValue ioValue = null; try { <START> ioValue = xbeeDevice.getDIOValue(IOLine.DIO0_AD0); <END> } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } assertEquals(IOValue.HIGH, ioValue); }</code><technical_language>Do catch exceptions throw them, if this occurs test case is failing is need</technical_language>

Target:
public void testGetDIOValueSuccess() throws Exception { ATCommandResponse mockedResponse = Mockito.mock(ATCommandResponse.class); Mockito.when(mockedResponse.getResponseStatus()).thenReturn(ATCommandStatus.OK); Mockito.when(mockedResponse.getResponse()).thenReturn(new byte[1]); Mockito.doReturn(mockedResponse).when(xbeeDevice).sendATCommand((ATCommand)Mockito.any()); HashMap<IOLine, IOValue> dioValues = new HashMap<IOLine, IOValue>(); dioValues.put(IOLine.DIO0_AD0, IOValue.HIGH); IOSample mockedIOSample = Mockito.mock(IOSample.class); Mockito.when(mockedIOSample.hasDigitalValues()).thenReturn(true); Mockito.when(mockedIOSample.getDigitalValues()).thenReturn(dioValues); PowerMockito.whenNew(IOSample.class).withAnyArguments().thenReturn(mockedIOSample); IOValue ioValue = xbeeDevice.getDIOValue(IOLine.DIO0_AD0); assertEquals(IOValue.HIGH, ioValue); }
Source:
<code>public void convertSingleToStringWhenMultiValues() throws Exception { ResultSerializer resultSerializer = new DetailedResultSerializer(false); Collection<String> messages = resultSerializer.serialize(dummyServer(), dummyQuery(), numericResult()); assertThat(messages).hasSize(1); String message = messages.iterator().next(); JsonNode jsonNode = new ObjectMapper().readValue(message, JsonNode.class); assertThat(jsonNode.get("host").asText()).isEqualTo("host.example.net"); assertThat(jsonNode.get("source").asText()).isEqualTo("host.example.net"); assertThat(jsonNode.get("port").asInt()).isEqualTo(4321); assertThat(jsonNode.get("attributeName").asText()).isEqualTo("ObjectPendingFinalizationCount"); assertThat(jsonNode.get("className").asText()).isEqualTo("sun.management.MemoryImpl"); assertThat(jsonNode.get("objDomain").asText()).isEqualTo("ObjectDomainName"); assertThat(jsonNode.get("typeName").asText()).isEqualTo("type=Memory"); assertThat(jsonNode.get("typeNameMap").get("type").asText()).isEqualTo("Memory"); <START> assertThat(jsonNode.get("typeNameMap").size()).isEqualTo(1); <END> assertThat(jsonNode.get("values").get("ObjectPendingFinalizationCount").asLong()).isEqualTo(10L); assertThat(jsonNode.get("epoch").asLong()).isEqualTo(0L); assertThat(jsonNode.get("keyAlias").asText()).isEqualTo("MemoryAlias"); }</code><technical_language>this be: assertThat(jsonNode.get("typeNameMap")).hasSize(1);</technical_language>

Target:
public void convertSingleToStringWhenMultiValues() throws Exception { ResultSerializer resultSerializer = new DetailedResultSerializer(false); Collection<String> messages = resultSerializer.serialize(dummyServer(), dummyQuery(), numericResult()); assertThat(messages).hasSize(1); String message = messages.iterator().next(); JsonNode jsonNode = new ObjectMapper().readValue(message, JsonNode.class); assertThat(jsonNode.get("host").asText()).isEqualTo("host.example.net"); assertThat(jsonNode.get("source").asText()).isEqualTo("host.example.net"); assertThat(jsonNode.get("port").asInt()).isEqualTo(4321); assertThat(jsonNode.get("attributeName").asText()).isEqualTo("ObjectPendingFinalizationCount"); assertThat(jsonNode.get("className").asText()).isEqualTo("sun.management.MemoryImpl"); assertThat(jsonNode.get("objDomain").asText()).isEqualTo("ObjectDomainName"); assertThat(jsonNode.get("typeName").asText()).isEqualTo("type=Memory"); assertThat(jsonNode.get("typeNameMap").get("type").asText()).isEqualTo("Memory"); assertThat(jsonNode.get("typeNameMap")).hasSize(1); assertThat(jsonNode.get("values").get("ObjectPendingFinalizationCount").asLong()).isEqualTo(10L); assertThat(jsonNode.get("epoch").asLong()).isEqualTo(0L); assertThat(jsonNode.get("keyAlias").asText()).isEqualTo("MemoryAlias"); }
Source:
<code>public <START> SubchainInfo(DiskImage <END> baseImage, DiskImage topImage) { this.baseImage = baseImage; this.topImage = topImage; }</code><technical_language>add storage domain id arg init in ctor. need init base/top image id img grp id; otherwise, if this ctos calling id getters, NPE id guaranteed some point</technical_language>

Target:
public SubchainInfo(DiskImage baseImage, DiskImage topImage) { this.baseImage = baseImage; this.topImage = topImage; this.baseImageId = baseImage.getImageId(); this.topImageId = topImage.getImageId(); this.storageDomainId = baseImage.getStorageIds().get(0); }
Source:
<code>public RsSimple(final Iterable<String> head, final InputStream body) { super( <START> new RsOf( <END> () -> head, () -> body ) ); }</code><technical_language>@fanifieiev above</technical_language>

Target:
public RsSimple(final Iterable<String> head, final InputStream body) { super(new ResponseOf(head, body)); }
Source:
<code>public void getChunksReturnsEqualSizedChunks() { HARegionQueue spy = spy(haRegionQueue); addEvents(); eventIDS.add(mock(EventID.class)); eventIDS.add(mock(EventID.class)); Collection<List<EventID>> myChunks = spy.getChunks(eventIDS, 2); <START> assertThat(myChunks.size()).isEqualTo(3); <END> for (List<EventID> chunk : myChunks) { assertThat(chunk.size()).isEqualTo(2); } }</code><technical_language>this 3 replaced a calculated value, 2 for max chunk size extracted a variable? I eventIDS.size()/maxChunkSize correct value</technical_language>

Target:
public void getChunksReturnsEqualSizedChunks() { HARegionQueue spy = spy(haRegionQueue); addEvents(); eventIDs.add(mock(EventID.class)); eventIDs.add(mock(EventID.class)); int maxChunkSize = 2; Collection<List<EventID>> myChunks = spy.getChunks(eventIDs, maxChunkSize); assertThat(myChunks.size()).isEqualTo(eventIDs.size() / maxChunkSize); for (List<EventID> chunk : myChunks) { assertThat(chunk.size()).isEqualTo(maxChunkSize); } }
Source:
<code>private void index(Object entity, Session session, InstanceInitializer sessionInitializer, ConversionContext conversionContext) throws InterruptedException { if ( Thread.currentThread().isInterrupted() ) { throw new InterruptedException(); } Serializable id = session.getIdentifier( entity ); Class<?> clazz = HibernateHelper.getClass( entity ); EntityIndexBinding entityIndexBinding = entityIndexBindings.get( clazz ); if ( entityIndexBinding == null ) { return; } EntityIndexingInterceptor interceptor = entityIndexBinding.getEntityIndexingInterceptor(); if ( interceptor != null ) { IndexingOverride onAdd = interceptor.onAdd( entity ); switch ( onAdd ) { case REMOVE: case SKIP: return; } } DocumentBuilderIndexedEntity docBuilder = entityIndexBinding.getDocumentBuilder(); TwoWayFieldBridge idBridge = docBuilder.getIdBridge(); String idPropertyName = docBuilder.getIdPropertyName(); <START> conversionContext.pushProperty( docBuilder.getIdFieldName() ); <END> String idInString = null; try { idInString = conversionContext .setClass( clazz ) .twoWayConversionContext( idBridge ) .objectToString( id ); } finally { conversionContext.popProperty(); } AddLuceneWork addWork = docBuilder.createAddWork( tenantId, clazz, entity, id, idInString, sessionInitializer, conversionContext ); backend.enqueueAsyncWork( addWork ); }</code><technical_language>Care explain this change? (maybe a separate commit in order)</technical_language>

Target:
private void index(Object entity, Session session, InstanceInitializer sessionInitializer, ConversionContext conversionContext) throws InterruptedException { if ( Thread.currentThread().isInterrupted() ) { throw new InterruptedException(); } Serializable id = session.getIdentifier( entity ); Class<?> clazz = HibernateHelper.getClass( entity ); EntityIndexBinding entityIndexBinding = entityIndexBindings.get( clazz ); if ( entityIndexBinding == null ) { return; } EntityIndexingInterceptor interceptor = entityIndexBinding.getEntityIndexingInterceptor(); if ( interceptor != null ) { IndexingOverride onAdd = interceptor.onAdd( entity ); switch ( onAdd ) { case REMOVE: case SKIP: return; } } DocumentBuilderIndexedEntity docBuilder = entityIndexBinding.getDocumentBuilder(); TwoWayFieldBridge idBridge = docBuilder.getIdBridge(); String idPropertyName = docBuilder.getIdPropertyName(); if ( idPropertyName != null ) { conversionContext.pushProperty( idPropertyName ); } String idInString = null; try { idInString = conversionContext .setClass( clazz ) .twoWayConversionContext( idBridge ) .objectToString( id ); } finally { if ( idPropertyName != null ) { conversionContext.popProperty(); } } AddLuceneWork addWork = docBuilder.createAddWork( tenantId, clazz, entity, id, idInString, sessionInitializer, conversionContext ); backend.enqueueAsyncWork( addWork ); }